gpt4 book ai didi

javascript - 继承后正确保持构造函数

转载 作者:搜寻专家 更新时间:2023-11-01 04:27:39 24 4
gpt4 key购买 nike

我注意到这个有趣的问题:

function a() { this.aprop = 1; }
function b() { this.bprop = 2; }
b.prototype = new a(); // b inherits from a
var x = new b(); // create new object with the b constructor
assert(x.constructor == b); // false
assert(x.constructor == a); // true

据我所知,x.constructor应该是b,但是当b时实际上是a通过其原型(prototype)继承自a?有没有一种方法可以在不搞砸我的构造函数的情况下从 a 继承?

最佳答案

这是因为 b.prototype.constructor 在第 3 行被分配了 new a().constructor。您可以在以下行中更改此属性:

function a() { this.aprop = 1; }
function b() { this.bprop = 2; }
b.prototype = new a(); // b inherits from a
b.prototype.constructor = b; // <-- add this
var x = new b(); // create new object with the b constructor
assert(x.constructor == b); // false
assert(x.constructor == a); // true

关于javascript - 继承后正确保持构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4517882/

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