五种继承方式
1. 原型继承
function A() {
this.x = 100;
}
A.prototype.getX = function () {
console.log(this.x);
};
function B() {
this.y = 200;
}
B.prototype = new A
var b = new B;
console.log(b)
子类B想要继承父类A中的所有属性和方法(私有和公有),只需要让B.prototype=new A;
特点:它是把父类中私有的和公有的都继承到子类原型上
原型继承并不是把父类中的属性和方法克隆一份一模一样的给B,而是让B和A之间增加了原型链的连接,以后B的实例b想要A中的的getX方法,需要一级级的向上查找来使用,通过_ proto _子类可以改变父类的属性和方法
2. call继承
function B() {
// this -> b
A.call(this); // ->A.call(b) 把A执行让A中的this变为b
}
var b = new B;
console.log(b.x) // 100
console.log(b.getX()) // TypeError: b.getX is not a function
call继承把父类私有的属性和方法克隆一份一模一样的作为子类私有的属性
3. 冒充对象继承
function A() {
this.x = 100;
}
A.prototype.getX = function () {
console.log(this.x);
};
function B() {
// this -> b
var temp = new A;
for (var key in temp) {
this[key] = temp[key];
}
temp = null;
}
var b = new B;
console.log(b)
把父类的私有的和公有的克隆一份一模一样的给子类私有的
4. 混合模式继承
原理:原型继承+ call继承
function A() {
this.x = 100;
}
A.prototype.getX = function () {
console.log(this.x);
};
function B() {
A.call(this) // -> n.x = 100
}
B.prototype = new A; // -> B.prototype: x=100,getX
B.prototype.constructor = B;
var b = new B;
b.getX();
这种继承方式,会导致私有属性和公有属性重复
5.寄生组合式继承
私有的继承私有的(通过call)
公有的继承公有的(prototype上的继承prototype的,通过Object.create() )
function A() {
this.x = 100;
}
A.prototype.getX = function () {
console.log(this.x);
};
function B() {
A.call(this)
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
var b = new B;
b.getX();