javascript - 冻结构造函数原型的副作用

Zso*_*bor 7 javascript prototype freeze

我注意到冻结构造函数的原型有副作用,基本上破坏了构造函数链接:

function A(x) {
    this.x=x;
}

function B(x, y) {
    A.call(this, x);
    this.y=y;
}
B.prototype = new A();
Object.freeze(B.prototype);
b=new B(1,2)
// I expected b.x to be 1 here but it's undefined
Run Code Online (Sandbox Code Playgroud)

这是一个演示问题的小提琴:

http://jsfiddle.net/jhpxv20b/2/

有没有一个很好的理由为什么bx最终未定义?

如果这不是一个bug,那么x2如何在小提琴中是1?

Zso*_*bor 2

这个答案很好地解释了这里发生的事情。

特别是,我的错误是我没有意识到在这一行之后

B.prototype = new A();
Run Code Online (Sandbox Code Playgroud)

B.prototype 成为具有“x”属性的对象(即,尽管 B.prototype.x === undefined 为 true,但 B.prototype.hasOwnProperty('x') 也为 true)。

我将上面的行更改为:

B.prototype = Object.create(A.prototype);
Run Code Online (Sandbox Code Playgroud)

这允许我冻结 B.prototype 而不会破坏构造函数链接。

感谢 Quantas 94 Heavy 为我指明了正确的方向。