Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anything wrong with Object.freeze() on a JavaScript prototype?

Is there anything wrong with calling Object.freeze on a constructor's prototype in JavaScript?

I was just thinking that since the prototype is shared amongst all instances, perhaps I can ensure that nobody overwrites anything in the prototype by freezing it, since overwriting something on the prototype affects every instance. So for instance, something like the following:

function MyConstructor() {
  // Stuff
}

MyConstructor.prototype = {
  method1() {
    // more stuff
  },
  method2() {
    // even more stuff
  },
  someArray: ['some', 'values'],
  someValue: 'value'
}

Object.freeze(MyConstructor.prototype);
like image 911
The Qodesmith Avatar asked Oct 30 '22 13:10

The Qodesmith


1 Answers

If you freeze the prototype you also freeze the the objects extending it, so they won't be able to override those properties defined in the prototype

This gist is a test to showcase the problem

like image 191
alebianco Avatar answered Nov 11 '22 12:11

alebianco