原型链继承
原型链继承缺点:
1 子类从父类继承的属性和方法变成了共享的
2 继承时子类无法给父类传递参数
function Box() { //Box 构造
this.name = 'Lee';
}
function Desk() { //Desk 构造
this.age = 100;
}
Desk.prototype = new Box(); //Desc 继承了Box,通过原型,形成链条
var desk = new Desk();
alert(desk.age);
alert(desk.name); //得到被继承的属性
function Table() { //Table 构造
this.level = 'AAAAA';
}
Table.prototype = new Desk(); //继续原型链继承
var table = new Table();
alert(table.name); //继承了Box 和Desk
原型链继承流程图
在JavaScript 里,被继承的函数称为超类型(父类,基类也行,其他语言叫法),继承的
函数称为子类型(子类,派生类)。继承也有之前问题,比如字面量重写原型会中断关系,使
用引用类型的原型,并且子类型还无法给超类型传递参数。
对象冒充
缺点:无法继承父类的原型属性与方法
优点:可以向父类传参
function Box(age) {
this.name = ['Lee', 'Jack', 'Hello']
this.age = age;
}
function Desk(age) {
Box.call(this, age); //对象冒充,给超类型传参
}
var desk = new Desk(200);
alert(desk.age);
alert(desk.name);
desk.name.push('AAA'); //添加的新数据,只给desk
alert(desk.name);
组合继承(原型链继承+对象冒充)
function Box(age) {
this.name = ['Lee', 'Jack', 'Hello']
this.age = age;
}
Box.prototype.run = function () {
return this.name + this.age;
};
function Desk(age) {
Box.call(this, age); //对象冒充 继承父类构造函数里的实例属性 并可以向父类传递参数
}
Desk.prototype = new Box(); //原型链继承 继承父类的原型属性与方法
var desk = new Desk(100);
alert(desk.run());