// 父類構造函數 function Parent(color) { this.color = color; this.print = function() { console.log(this.color); } }
如今要編寫一個子類函數來繼承這個父類,以下:ios
// 子類構造函數 function Son(color) { Parent.call(this, color); }
上面代碼能夠看到,子類Son是經過Parent.call的方式去調用父類構造函數,而後把this對象傳進去,執行父類構造函數以後,子類Son就擁有了父類定義的color和print方法。es6
調用一下該方法,輸出以下:面試
// 測試 var son1 = new Son('red'); son1.print(); // red var son2 = new Son('blue'); son2.print(); // blue
function Flower() { this.colors = ['黃色', '紅色']; this.print = function () { console.log(this.colors) } } function Rose() { Flower.call(this); } var r1 = new Rose(); var r2 = new Rose(); console.log(r1.print()); // [ '黃色', '紅色' ] console.log(r2.print()); // [ '黃色', '紅色' ]
咱們如今有一個基類Flower,它有一個屬性colors,如今咱們把某一個實例的colors值改一下:函數
r1.colors.push('紫色'); console.log(r1.print()); // [ '黃色', '紅色', '紫色' ] console.log(r2.print()); // [ '黃色', '紅色' ]
function Parent() { this.color = 'red'; this.print = function() { console.log(this.color); } } function Son() { }
咱們有一個父類和一個空的子類;性能
Son.prototype = new Parent(); Son.prototype.constructor = Son;
接着咱們把子函數的原型屬性賦值給了父函數的實例;測試
var son1 = new Son(); son1.print(); // red
Son.prototype = new Parent(); Son.prototype.constructor = Son;
function Flower() { this.colors = ['黃色', '紅色']; this.print = function () { console.log(this.colors) } } function Rose() {} Rose.prototype = new Flower(); Rose.prototype.constructor = Rose; var r1 = new Rose(); var r2 = new Rose(); console.log(r1.print()); // [ '黃色', '紅色' ] console.log(r1.print()); // [ '黃色', '紅色' ] r1.colors.push('紫色'); console.log(r1.print()); // [ '黃色', '紅色', '紫色' ] console.log(r2.print()); // [ '黃色', '紅色', '紫色' ]
function Parent(color) { this.color = color; } Parent.prototype.print = function() { console.log(this.color); } function Son(color) { Parent.call(this, color); } Son.prototype = new Parent(); Son.prototype.constructor = Son; var son1 = new Son('red'); son1.print(); // red var son2 = new Son('blue'); son2.print(); // blue
var obj = { color: 'red', print: function() { console.log(this.color); } }; var son1 = Object.create(obj); son1.print(); // red var son2 = Object.create(obj); son2.print(); // red
寄生式繼承本質上仍是原型鏈繼承,Object.create(obj);方法意思是以obj爲原型構造對象,因此寄生式繼承不須要構造函數,可是一樣有着原型鏈繼承的優缺點,也就是它把全部的屬性和方法都共享了。this
function Parent(color) { this.color = color; } Parent.prototype.print = function() { console.log(this.color); } function Son(color) { Parent.call(this, color); } Son.prototype = Object.create(Parent.prototype); Son.prototype.constructor = Son; var son1 = new Son('red'); son1.print(); // red var son2 = new Son('blue'); son2.print(); // blue