Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent changes to a prototype?

In this code, the prototype can still change.

How I can prevent changes to the prototype?

var a = {a:1}
var b={b:1}
var c = Object.create(a)
Object.getPrototypeOf(c) //a
c.__proto__ = b;
Object.getPrototypeOf(c) //b
var d = Object.create(null)
Object.getPrototypeOf(d) //null
d.__proto__ = b;
Object.getPrototypeOf(d) //null
like image 953
Oksana Avatar asked Nov 08 '16 13:11

Oksana


1 Answers

How I can prevent changes to the prototype?

I assume you are not talking about mutating the prototype object itself, but overwriting the prototype of an existing object.

You can use Object.preventExtensions() to prevent that:

var a = {a:1}
var b = {b:1}
var c = Object.create(a)
Object.preventExtensions(c) 
console.log(Object.getPrototypeOf(c)) //a
c.__proto__ = b; // Error

But that also means you cannot add any new properties to it. You could also use Object.freeze() or Object.seal() depending on your needs, which restrict modifications to the object even more.

There are no other ways though.

like image 145
Felix Kling Avatar answered Oct 15 '22 20:10

Felix Kling