什么是借用构造函数
在解决原型中包含引用类型值所带来问题的过程中,开发人员开始使用一种叫做借用构造函数的技术。即在子类构造函数的内部调用超类型构造函数(被继承的类叫超类,继承超类的叫子类)。
函数只不过是在特定环境中执行代码的对象,因此通过apply()和call()方法也可以在将来新创建的对象上执行构造函数。
例如:
//超类
function SuperType(){
this.color=["red","blue","green"]
}
//子类
function SubType(){
//继承 SuperType
//在(未来将要)新创建的 SubType 实例的环境下调用了 SuperType 构造函数
SuperType.call(this); //this作为函数上下文对象,apply、call 方法都会使函数立即执行
}
var instance1 = new SubType();
instance1.color.push("black");
console.log(instance1);
console.log(instance1.color); //["red", "blue", "green", "black"]
//SubType 的每个实例就都会具有自己的 colors 属性的副本
var instance2 = new SubType();
console.log(instance2.color); //["red", "blue", "green"]
传递参数
借用构造函数有一个很大的优势,即可以在子类构造函数中向超类型构造函数传递参数。
例如:
function SuperType(name){
this.name = name;
}
function SubType(){
//继承了 SuperType,同时还传递了参数
SuperType.call(this, "Nicholas"); //实例属性
this.age = 29;
}
var instance = new SubType();
alert(instance.name); //"Nicholas";
alert(instance.age); //29
借用构造函数的问题
方法都在构造函数中定义,因此函数复用就无从谈起了。而且,在超类型的原型中定义的方法,对子类型而言也是不可见的,结果所有类型都只能使用构造函数模式。