javascript --- 類、class、事件委托的編程風格

類風格:

// 父類
function Widget(width, height) {this.width = width || 50;this.height = height || 50;this.$elem = null;
}
Widget.prototype.render = function($where) {if(this.$elem) {this.$elem.css({width: this.width + "px",height: this.height + "px"}).appendTo($where);}
};// 子類
function Button(width, height, label) {// 調用父類(Widget)的構造函數Widget.call(this, width, height);this.label = label || "Default";this.$elem = $("<button>").text(this.label);
}// 讓Button"繼承"Widget(Button可以使用Widget原型上的方法,本例中是render方法)
Button.prototype = Object.create(Widget.prototype);// 重寫render
Button.prototype.render = function($where) {// 調用父類(Widget)的render方法Widget.prototype.render.call(this, $where);  this.$elem.click(this.onClick.bind(this)); // 監聽點擊事件
};Button.prototype.onClick = function(evt) {console.log("Button '" + this.label + " 'clicked!" );
};$(document).ready(function() {var $body = $(document.body);var btn1 = new Button(125, 30, "Hello" );var btn2 = new Button(150, 40, "World");btn1.render($body);btn2.render($body);
});// 注:用到了jquery故需要導入cdn <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

在這里插入圖片描述
在這里插入圖片描述
上述代碼,首先定義了一個Widget的父類,然后使用使用在constructor中使用call方法(作用域綁定到當前)調用父類Widget的初始化…并添加了一個新的$elem(即Butoon標簽).
在Button的原型上,使用Object.create()方法繼承父類的原型方法(render).并新增了一個(按鈕特有的)點擊功能.

說明:上面是一個仿照類實現的方法,其實就是使用Widget.call 和Widget.prototype.render.call在Button函數中調用Widget…
用書上的原話說就是…丑陋的顯示多態

ES6的class語法糖實現:

class Widget{constructor(width, height) {this.width = width || 50;this.heigth = height || 50;this.$elem = null;}// 很巧妙的render...render($where) {if(this.$elem) {this.$elem.css({width: this.width + "px",height: this.height + "px"}).appendTo($where);}}
}
class Button extends Widget{constructor(width, height, label) {super( width, height);this.label = label || "Default";this.$elem = $("<button>").text(this.label);  // 生成一個<button> 內容是label}render($where) {  // $where 是調用時傳入的參數super.render($where);   // 調用父類Widget的renderthis.$elem.click(this.onClick.bind(this));}onClick(evt) {console.log("Button ' " + this.label + " ' clicked!");}
}
$(document).ready(function(){var $body = $(document.body);var btn1 = new Button(125, 30, "Hello" );var btn2 = new Button(150, 40, "World" );btn1.render($body);btn2.render($body);})
//說明: 關鍵是super替代了偽類中的call方法...變得更簡潔(at least看上去是這樣...)

委托控件對象:

var Widget = {init: function(width, height){this.width =width || 50;this.height = height || 50;this.$elem = null;},insert: function($where) {if(this.$elem){this.$elem.css({width: this.width + "px",height: this.heigth + "px"}).appenTo($where);}}
};
// 還是定義一個Widget對象,, 使用委托(Object.create)順著原型鏈[[prototype]]由下而上讀取方法
var Button = Object.create(Widget);Button.setup = function(width, height, label) {this.init(width, height);  // Button無init方法,順著原型鏈找到了Widget中的init.this.label = label || "Default";this.$elem = $('<button>').text(this.label);
};
Button.build = function($where) {this.insert($where);this.$elem.click(this.onClick.bind(this));  // this.onClick實際上是Button.onClick
};
Button.onClick = function(evt) {console.log("Button '" + this.label + "' clicked!" );
};
$(document).ready(function(){var $body = $(document.body);var btn1 = Object.create(Button);btn1.setup(123, 30, 'Hello');var btn2 = Object.create(Button);btn2.setup(150, 40, 'World');btn1.build($body);btn2.build($body);
});
// 很美的方式

參考《你不知道的JavaScript》(上卷) P174 ~P177

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/251229.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/251229.shtml
英文地址,請注明出處:http://en.pswp.cn/news/251229.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

在線獲取UUID

http://fir.im/udid轉載于:https://www.cnblogs.com/mtjbz/p/8116576.html

堆和堆排序

堆和優先隊列 普通隊列&#xff1a;FIFO&#xff0c;LILO 優先隊列&#xff1a;出隊順序和入隊順序無關&#xff0c;和優先級相關。一個典型應用就是操作系統中。動態選擇優先級高的任務執行 堆的實現 最典型的堆就是二叉堆&#xff0c;就像是一顆二叉樹。這個堆的特點&#xf…

ES5-1 發展史、ECMA、編程語言、變量、JS值

1. 5大主流瀏覽器及內核&#xff08;自主研發&#xff09; 瀏覽器內核IEtridentChromewebkit blinkSafariwebkitFirefoxgeckoOperapresto 2. 瀏覽器的歷史 和 JS誕生 1989-1991 WorldWideWeb&#xff08;后來為了避免與萬維網混淆而改名為Nexus&#xff09;是世界上第一個網頁…

javascript --- 使用對象關聯簡化整體設計

在某個場景中,我們有兩個控制器對象: 1.用來操作網頁中的登錄表單; 2.用來與服務器進行通信. 類設計模式 // 把基礎的函數定義在名為Controller的類中,然后派生兩個子類LoginController和AuthController. // 父類 function Controller() {this.errors []; } Controller.prot…

javascript --- polyfill中幾個常用方法

ES6中,新增了許多有用的方法,下面分享幾個ES6之前得版本寫的polyfill Number.EPSILON: // 機器精度,并判斷2個數是否相等 if(!Number.EPSILON){Number.EPSILON math.pow(2, -52); }function numberCloseEnoughToEqual(n1, n2) {return Math.abs(n1 - n2 ) < Number.EPSIL…

[Usaco2010 Nov]Visiting Cows

題目描述 經過了幾周的辛苦工作,貝茜終于迎來了一個假期.作為奶牛群中最會社交的牛,她希望去拜訪N(1<N<50000)個朋友.這些朋友被標號為1..N.這些奶牛有一個不同尋常的交通系統,里面有N-1條路,每條路連接了一對編號為C1和C2的奶牛(1 < C1 < N; 1 < C2 < N; C1…

ES5-2 語法、規范、錯誤、運算符、判斷分支、注釋

1. 錯誤 MDN錯誤列表 Uncaught SyntaxError: Unexpected token ) // 語法錯誤 Uncaught ReferenceError: a is not defined // 引用錯誤等類型 Uncaught TypeError: Cannot read property toString of null出現一個語法錯誤&#xff0c;則一行代碼都不會執行&#xff08;檢查…

新單詞 part 4

part 41.veto 英[?vi:t??]美[?vi:to?]n. 行使否決權; 否決權&#xff0c;否認權; 否決理由;vt. 否決&#xff0c;不同意; 不批準&#xff0c;禁止;vi. 否決; 禁止;2.acoustics 英[??ku:st?ks]美[??kust?ks]n. 聲學; &#xff08;傳聲系統的&#xff09; 音響效果; 聲…

unity深度查找某個子物體和遍歷所有子物體方法

本文總結一下關于unity的查找子物體的方法 首先說明一下這里將講三種查找子物體方法&#xff1a; 查找固定路徑的某一個子物體的方法、通過名字深度查找某個子物體的方法、查找父物體下所有子物體的方法。 第一:查找固定路徑的某一個子物體的方法 對于已知的路徑可以直接用go.t…

javascript --- JSON字符串化

工具函數JSON.stringify()將JSON對象序列化為字符串時也用到了ToString. 看下面的代碼: console.log(JSON.stringify(42)); console.log(JSON.stringify("42")); console.log(JSON.stringify(null)); console.log(JSON.stringify(true));所有安全的JSON值都可以使用…

靜態鏈接和動態鏈接

靜態鏈接和動態鏈接 靜態鏈接方法&#xff1a;靜態鏈接的時候&#xff0c;載入代碼就會把程序會用到的動態代碼或動態代碼的地址確定下來 靜態庫的鏈接可以使用靜態鏈接&#xff0c;動態鏈接庫也可以使用這種方法鏈接導入庫 動態鏈接方法&#xff1a;使用這種方式的程序并不在一…

ES5-3 循環、引用值初始、顯示及隱式類型轉換

1. 循環 for循環的三個參數abc&#xff0c;a只執行一次&#xff0c;c在每次循環后執行 // 打印0-100的質數 1不是質數 var list [2] for (var i 3; i < 100; i i 2) {var flag falsefor (var j 0; j < list.length; j) {var cur list[j]if (i % cur 0 &…

hihocoder 二分

題目 一個簡單的二分&#xff0c;只是想說明一下&#xff0c;如若要查找一個數組中某個數的下標可以直接用lower_bound()這個函數。只是要考慮到要查找的數不在數組中的這種情況。 #include <cstdio> #include <iostream> #include <algorithm> using namesp…

ubuntu開啟ssh服務

更新資源列表&#xff1a;sudo apt-get update -> 輸入管理員密碼 安裝openssh-server: sudo apt-get install openssh-server 查看 ssh服務是否啟動&#xff1a;sudo ps -e |grep ssh 啟動ssh服務&#xff1a; sudo service ssh start 轉載于:https://www.cnblogs.com/ver…

javascript --- 判斷只有1個為真

下面寫一個用于判斷只有一個為真的函數: function onlyOne(a,b,c){return !!((a && !b && !c) ||(!a && b && !c) || (!a && !b && c)); } var a true; var b false;onlyOne(a,b,b) // true onlyOne(a,b,a); // false上述…

13 代碼分割之import靜動態導入

前端首屏優化方案之一 項目構建時會整體打包成一個bundle的JS文件&#xff0c;而有的代碼、模塊是加載時不需要的&#xff0c;需要分割出來單獨形成一個文件塊chunk&#xff08;不會打包在main里&#xff09;&#xff0c;讓模塊懶加載&#xff08;想加載時才加載&#xff09;&a…

2018.01.01(數字三角形,最長上升子序列等)

2017.12.24 簡單的動態規劃 1.數字三角形(算法引入) 題目描述&#xff1a;下圖所示是一個數字三角形&#xff0c;其中三角形中的數值為正整數&#xff0c;現規定從最頂層往下走到最底層&#xff0c;每一步可沿左斜線向下或右斜線向下走。設三角形有n層&#xff0c;編程計算出從…

Mac iOS 允許從任何來源下載應用并打開

一個快捷的小知識點&#xff0c;mark&#xff01; 允許從任何來源下載應用并打開&#xff0c;不用手動去允許&#xff0c;更加簡潔&#xff01; 只需一行命令 sudo spctl --master-disable 1.正常情況下&#xff0c;打開偏好設置&#xff0c;選擇安全性與隱私&#xff0c;界面是…

ES5-4 函數基礎與種類、形實參及映射、變量類型

模塊編程原則&#xff1a;高內聚&#xff0c;低耦合&#xff08;重復部分少&#xff09;&#xff0c;讓一個模塊有強的功能性、高的獨立性 → 單一責任制&#xff0c;用函數進行解耦合。 1. 函數命名規則 不能以數字開頭可以以字母_$開頭包含數字小駝峰命名法 函數聲明一定有…

javascript --- 抽象相等

字符串和數字之間的相等比較 var a 42; var b "42";a b; // false a b; // trueES5規范11.9.3.4-5定義如下: (1)如果Type(x)是數字,Type(y)是字符串,則返回 x ToNumber(y) 的結果 (2)如果Type(x)是字符串,Type(x)是數字,則返回 ToNumber(x) y 的結果// 總結…