7

I noticed that freezing the prototype of a constructor function had a side effect that basically broke constructor chaining:

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

Here is a fiddle to demonstrate the problem:

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

Is there a good reason why b.x is undefined at the end?

If this is not a bug, then how come x2 is 1 in the fiddle?

Zsombor
  • 141
  • 7
  • 2
    Although your question doesn't have exactly the same code, [this question](http://stackoverflow.com/questions/19698533/creating-new-objects-from-frozen-parent-objects/19698581#19698581) explains why this is the case. – Qantas 94 Heavy Oct 04 '14 at 02:39

1 Answers1

2

This answer gives a good explanation for what is happening here.

In particular, my mistake was that I did not realize that after this line

B.prototype = new A();

B.prototype became an object that had an 'x' property (i.e. despite the fact that B.prototype.x === undefined is true, B.prototype.hasOwnProperty('x') is also true).

I changed the above line to this:

B.prototype = Object.create(A.prototype);

and this allows me to freeze B.prototype without breaking the constructor chaining.

Thanks to Quantas 94 Heavy for pointing me to the right direction.

Community
  • 1
  • 1
Zsombor
  • 141
  • 7