直接上代码
Parent.prototype.getName = function () {
console.log(this.name)
}
function Child (name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child(‘kevin’, ‘18’);
child1.colors.push(‘black’);
console.log(child1.name); // kevin
console.log(child1.age); // 18
console.log(child1.colors); // [“red”, “blue”, “green”, “black”]
var child2 = new Child(‘daisy’, ‘20’);
console.log(child2.name); // daisy
console.log(child2.age); // 20
console.log(child2.colors); // [“red”, “blue”, “green”]
这是一段组合继承的代码
Child.prototype.constructor = Child;
为什么要对constructor指正呢
这就得从constructor属性入手解答
我们举个简单例子
function Person() {
}
var person = new Person();
console.log(person.constructor === Person); // true
Person函数(手画请见谅)
当获取person.constructor函数时,其实Person函数是没有constructor属性的,当不能获取到时就会从person的原型也就是Person.prototype上读取,刚好Person.prototype有,所以
person.constructor === Person.prototype.constructor
然后回归正题
Child.prototype = new Parent();
如果没有Child.prototype.constructor = Child;这句话指正的话
这时候
console.log(Child.prototype.constructor === Person.prototype.constructor);//true
本来Child.prototype.constructor 应该指向Child.prototype的实例,比如
var child1 = new Child();
Child.prototype.constructor应该指向child1.constructor
console.log(child1.constructor === Child.prototype.constructor);//true
可这时候两个都等于true,那这样constructor的指向就出现了双向,这是不符合的
所以这时候就应该明确constructor的指向
Child.prototype.constructor = Child;
最后来做个简单的验证
function Person() {
}
function Child() {
}
Child.prototype = new Person();
Child.prototype.constructor = Child;
let child1 = new Child();
console.log(Child.prototype.constructor === Person.prototype.constructor);//false