先贴一段《javascript高级程序语言设计》上关于组合继承的代码:
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
console.log(this.name);
};
function SubType(name, age){
SuperType.call(this.age);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType; //why?
SubType.prototype.sayAge = function(){
console.log(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
console.log(instance1.colors); // red, blue, green, black
instance1.sayName(); // Nicholas
instance1.sayAge(); // 29
var instance2 = new SubType("Greg", 27);
console.log(instance1.colors); // red, blue, green
instance1.sayName(); // Greg
instance1.sayAge(); // 27
这里大部分我都能理解,但是中间那里,为什么需要SubType.prototype.constructor = SubType
,我知道如果不这样子的话SubType.prototype.constructor
的值是SuperType
。但是其实不这样做也能达成继承啊,这样子做的用意是什么?
如你所说,继承和这一句确实没什么关系。
但是面向对象编程里除了继承,还有一个对象识别。有时你需要判断一个对象的类别,在js 里你如何获知一个对象的类别名呢?一个重要的方法就是取其
constructor
属性。所以,不加也可以,但加了绝对有好处。