gpt4 book ai didi

javascript - 对象的构造函数属性的奇怪行为

转载 作者:行者123 更新时间:2023-12-02 22:44:00 24 4
gpt4 key购买 nike

在下面的代码中,为什么'scotty.constructor'设置为'Dog'函数?对象的构造函数属性一般是如何设置的?它是否设置为使用“new”创建对象的函数?如果是这样,则 scotty 是由“ShowDog”创建的,最后一行应该将其作为输出。

// Dog Constructor
function Dog(name, breed, weight) {
this.name = name;
this.breed = breed;
this.weight = weight;
}


// Dog Prototype
Dog.prototype.species = 'Canine';

Dog.prototype.bark = function() {
if (this.weight > 25) {
console.log(this.name + ' says Woof!');
} else {
console.log(this.name + ' says Yip!');
}
};

Dog.prototype.run = function() {
console.log('Run!');
};

// ShowDog Constructor
function ShowDog(name, breed, weight, handler) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.handler = handler;
}

// ShowDog Prototype
ShowDog.prototype = new Dog();

ShowDog.prototype.league = 'Webville';

ShowDog.prototype.stack = function() {
console.log('Stack');
};

// ShowDog Instance
var scotty = new ShowDog('Scotty', 'Scotish Terrier', 15, 'Cookie');
console.log('Scotty\'s constructor is ' + scotty.constructor);

最佳答案

对象没有自己的 构造函数属性,它取自它们的protos。所以,如果没有这一行:

ShowDog.prototype = new Dog();

继承图是

enter image description here

一旦将new Dog分配给prototype(从而丢弃其当前值),图片将变为:

enter image description here

并且构造函数值(Dog)取自scotty.__proto__.__proto__

要使继承按预期工作,您必须手动分配构造函数:

ShowDog.prototype = new Dog()
ShowDog.prototype.constructor = ShowDog

产生以下图表:

enter image description here

关于javascript - 对象的构造函数属性的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58483675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com