How to prevent changes to a prototype?

馋奶兔 提交于 2020-02-23 10:41:32

问题


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

回答1:


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.




回答2:


Yes we can ,use Object.freeze.

Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

See this freeze reference

check this snippet

var a = {a:1}
var b={b:1}
var c = Object.create(a)
Object.getPrototypeOf(c) //a
Object.freeze(c);
c.__proto__ = b;//throws error now
console.log(Object.getPrototypeOf(c)) //a
var d = Object.create(null)
Object.getPrototypeOf(d) //null
d.__proto__ = b;
Object.getPrototypeOf(d) //null

Hope this helps



来源:https://stackoverflow.com/questions/40488025/how-to-prevent-changes-to-a-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!