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?
freeze() method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.
freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.
So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.
Object. freeze() makes an object immune to everything even little changes cannot be made. Object. seal() prevents from deletion of existing properties but cannot prevent them from external changes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With