基本概念
借用构造函数(constructor stealing)进行继承的基本思想就是:在子类型构造函数的内部调用超类型构造函数。
那么,如何调用?函数只不过是在特定环境中执行代码的对象,因此通过使用apply()和call()方法也可以在(将来)新创建的对象上执行构造函数。
示例代码
function SuperType() {
this.number = [1, 2, 3];
}
function SubType() {
SuperType.call(this);
}
var instance1 = new SubType();
instance1.number.push(4);
instance1.number; // "1,2,3,4"
var instance2 = new SubType();
instance2.number; // "1,2,3"
构造函数继承的优势:可以传递参数
function SuperType(name) {
this.name = name;
}
function SubType() {
Super.call(this, "MirrorAvatar");
this.age = 3;
}
var instance = new SuperType();
instance.name; //MirrorAvatar
instance.age; //3
借用构造函数继承的问题
- 方法都在构造函数中定义,函数无复用性;
- 在超类型的原型中定义的方法,对子类型而言也是不可见的,结果所有类型都只能使用构造函数模式。
以上,构造函数的技术很少单独使用。