Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Side-effects of freezing a constructor prototype

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?

like image 209
Zsombor Avatar asked Oct 04 '14 02:10

Zsombor


People also ask

What is the purpose of freeze method in JavaScript?

freeze() method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.

Why would you freeze an object?

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.

Is a constructor a prototype in JavaScript?

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.

What's the difference between object seal and object freeze methods?

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.


1 Answers

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.

like image 113
Zsombor Avatar answered Nov 15 '22 01:11

Zsombor