js prototype.constructor指正

本文通过代码示例探讨了JavaScript中组合继承时为何需要对`Child.prototype.constructor`进行指正,解释了`constructor`属性的工作原理,以及如果不进行指正可能导致的双向引用问题。通过对`Person`和`Child`构造函数的分析,强调了明确`constructor`指向的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值