寫在前面
本文講解JavaScript各種繼承方式和優缺點。
注意:
跟《JavaScript深入之創建對象》一樣,更像是筆記。
哎,再讓我感嘆一句:《JavaScript高級程序設計》寫得真是太好了!
1.原型鏈繼承
function Parent () { this.name = 'kevin';}Parent.prototype.getName = function () { console.log(this.name);}function Child () {}Child.prototype = new Parent();var child1 = new Child();console.log(child1.getName()) // kevin問題:
1.引用類型的屬性被所有實例共享,舉個例子:
function Parent () { this.names = ['kevin', 'daisy'];}function Child () {}Child.prototype = new Parent();var child1 = new Child();child1.names.push('yayu');console.log(child1.names); // ["kevin", "daisy", "yayu"]var child2 = new Child();console.log(child2.names); // ["kevin", "daisy", "yayu"]2.在創建 Child 的實例時,不能向Parent傳參
2.借用構造函數(經典繼承)
function Parent () { this.names = ['kevin', 'daisy'];}function Child () { Parent.call(this);}var child1 = new Child();child1.names.push('yayu');console.log(child1.names); // ["kevin", "daisy", "yayu"]var child2 = new Child();console.log(child2.names); // ["kevin", "daisy"]優點:
1.避免了引用類型的屬性被所有實例共享
2.可以在 Child 中向 Parent 傳參
舉個例子:
function Parent (name) { this.name = name;}function Child (name) { Parent.call(this, name);}var child1 = new Child('kevin');console.log(child1.name); // kevinvar child2 = new Child('daisy');console.log(child2.name); // daisy缺點:
方法都在構造函數中定義,每次創建實例都會創建一遍方法。
3.組合繼承
原型鏈繼承和經典繼承雙劍合璧。
function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () { console.log(this.name)}function Child (name, age) { Parent.call(this, name); this.age = age;}Child.prototype = new Parent();var child1 = new Child('kevin', '18');child1.colors.push('black');console.log(child1.name); // kevinconsole.log(child1.age); // 18console.log(child1.colors); // ["red", "blue", "green", "black"]var child2 = new Child('daisy', '20');console.log(child2.name); // daisyconsole.log(child2.age); // 20console.log(child2.colors); // ["red", "blue", "green"]優點:融合原型鏈繼承和構造函數的優點,是 JavaScript 中最常用的繼承模式。
4.原型式繼承
function createObj(o) { function F(){} F.prototype = o; return new F();}就是 ES5 Object.create 的模擬實現,將傳入的對象作為創建的對象的原型。
新聞熱點
疑難解答
圖片精選