gpt4 book ai didi

javascript - 如何防止更改原型(prototype)?

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:01 25 4
gpt4 key购买 nike

在此代码中,原型(prototype)仍然可以更改。

如何防止对原型(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

最佳答案

How I can prevent changes to the prototype?

我假设您不是在谈论改变原型(prototype)对象本身,而是覆盖现有对象的原型(prototype)。

您可以使用 Object.preventExtensions()为了防止这种情况:

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

但这也意味着您不能向它添加任何新属性。您也可以使用 Object.freeze()Object.seal()根据您的需要,这进一步限制了对对象的修改。

虽然没有其他方法。

关于javascript - 如何防止更改原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com