1.原型繼承
function A (){
this.name = 'Jack';
}
function B (){
this.type = 'type';
}
B.prototype = new A();
var b = new B();
console.log(b instanceof A); // true
2.構(gòu)造繼承
function A (){
this.name = 'Jack';
}
function B (){
this.type = 'type';
A.call(this);
}
var b = new B();
console.log(b instanceof A); // false
對比
- 構(gòu)造函數(shù)繼承的方法類似于復(fù)制酱塔,消耗內(nèi)存
- 構(gòu)造函數(shù)繼承的方法不能改變,而原型繼承可以通過改變原型鏈改變
3.組合模式
- 方法用原型繼承 (公用)
- 屬性用構(gòu)造繼承 (私有)
function A (){
this.name = 'Jack';
}
A.prototype.output = function(){
console.log(this.name);
}
function B (){
this.type = 'type';
A.call(this);
}
B.prototype = new A();
var b = new B();
b.output(); // 'Jack'