借用构造函数实现继承
由于通过原型链方式实现继承会存在缺陷(参考原型链继承), 所以有了借用构造函数实现继承。
借用构造函数实现方式如下:
function SuperType() { this.colors = ["red", "blue", "green"]; } function SubType() { SuperType.call(this); } var instance1 = new SubType(); instance1.colors.push("black"); //"red", "blue", "green", "black" console.log(instance1.colors); var instance2 = new SubType(); console.log(instance2.colors); //"red", "blue", "green"
通过在SubType构造函数中调用SuperType的call方法实现继承;
通过借用构造函数实现继承还可以向超类构造函数传递参数, 原型链继承不能向超类构造函数传递参数, 如下:
function SuperType(name) { this.colors = ["red", "blue", "green"]; this.name = name; } function SubType(name, age) { SuperType.call(this, name); this.age = age; } var instance1 = new SubType("Nicholas", 29); console.log(instance1.name); //Nicholas console.log(instance1.age); //29
此时, SubType将拥有SuperType所拥有的属性和方法。
但是通过借用构造函数实现继承时,SuperType原型对象中的属性和方法不会被继承, 如下。
function SuperType() { this.colors = ["red", "blue", "green"]; this.getColors = function() { return this.colors; } } SuperType.prototype.getSuperColors = function() { return this.colors; } SuperType.prototype.name = "Nicholas"; function SubType() { SuperType.call(this); } var instance1 = new SuperType(); console.log(instance1.getSuperColors()); //"red", "blue", "green" console.log(instance1.name); //"Nicholas" console.log(instance1.getSuperColors()); //"red", "blue", "green" var instance2 = new SubType(); console.log(instance2.getColors()); //"red", "blue", "green" console.log(instance2.name); //undefined console.log(instance2.getSuperColors()); //报错, 没有该方法
其中方法getColors方法是在SuperType构造函数中定义的, 所以SubType继承了,可以正常调用, 但是getSuperColors方法则是在SuperType的原型对象中定义的, 不能被继承;属性也是一样。
因为借用构造函数实现继承也有缺陷,所以有了组合继承。
备注: 例子及截图均来自《JAVASCRIPT高级程序设计:第3版》