dm03514
dm03514

Reputation: 55962

Freezing object __proto__ in v8

I was wondering if there were any caveats to freezing an object prototype. I was trying to create an immutable object but found out from the docs that

values that are objects can still be modified, unless they are also frozen

I am trying to make the __proto__ property immutable, my initial attempt involved freezeing the instance:

$ node --version
v0.12.7
$ node
> function Test() {}
undefined
> Test.prototype = {
...  hi: function() { return 'hello' }
... }
{ hi: [Function] }
> t = Object.freeze(new Test())
{}
> t
{}
> t.hello = 'hi'
'hi'
> t
{}
> t.hi
[Function]
> t.hi()
'hello'
> t.__proto__.hi = 'changed'
'changed'
> t.hi
'changed'

But when the prototype is frozen the __proto__ object is immutable as expected.

> Test.prototype = Object.freeze({
    ...  hi: function() { return 'hello' }
    ... })

Now instances of Test have an immutable __proto__ object (observed from shell). I was wondering are there any side effects to freezing an object prototype (perhaps involving multiple instances? or correct object instantiation??). The target environment is for node. Thank you

Upvotes: 0

Views: 332

Answers (1)

Andreas Rossberg
Andreas Rossberg

Reputation: 36098

The side effect of freezing a prototype is (tautologically) that the prototype is frozen. Whether that causes problems depends on how your application intends to use the prototype. There is nothing inherently wrong with it as far as the language is concerned. I would even consider it good style, if it wasn't for the fact that VMs sometimes still don't implement frozen objects very efficiently (they can be slower than regular objects under some circumstances, because for historic reasons they are considered a special case).

Upvotes: 3

Related Questions