gpt4 book ai didi

javascript - 用 object.create 定义的原型(prototype)的构造函数属性从哪里来?

转载 作者:行者123 更新时间:2023-11-28 02:26:16 25 4
gpt4 key购买 nike

function myObj(){
myOtherObj.call(this);
}

myObj.prototype = object.create(myOtherObj.prototype);

myObj.prototype 是否包含指向 myObj 函数的构造函数?如果是的话怎么办?

最佳答案

Does myObj.prototype contain a constructor pointing at myObj function? And if so how?

没有。 Object.create只会创建一个继承给定对象的对象。在您的情况下,它是 myOtherObj.prototype,并且可能具有现在继承的“构造函数”属性(myObj.prototype.constructor === myOtherObj.prototype .constructor === myOtherObj)。

这是 not necessary ,但如果您想调整属性,以便 (new myObj).constructor === myObj.prototype.constructor === myObj您可以通过将第二个参数传递给 Object.create 来做到这一点:

myObj.prototype = Object.create(myOtherObj.prototype, {
constructor: {value:myObj, writable:true, enumerable:false, configurable:true}
});

关于javascript - 用 object.create 定义的原型(prototype)的构造函数属性从哪里来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14883347/

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