gpt4 book ai didi

Javascript Object.seal() 不会抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:48:40 26 4
gpt4 key购买 nike

我想模拟类似固定对象的东西,这样就不能向对象添加新成员。 Object.seal(Obj) 似乎是正确的方法,但当我尝试创建新成员时它并没有抛出异常。成员没有被创建,但它悄无声息地发生。

var O = { a: 111 }
Object.seal(O)
O.b = 222 <------ here the exception is expected (trying to add a member "b")
O.a = 333
console.log(O) // { a: 333 }

为什么有人想要这种静默行为,为什么不抛出异常?

最佳答案

密封对象的赋值行为随浏览器而变化。例如,最新版本的 chrome 的行为符合您的预期。出于实际目的,可以安全地假设将成员添加到密封对象只会在严格模式下抛出异常。

;(function () {
'use strict';
var O = { a: 111 }
Object.seal(O)
O.b = 222
O.a = 333
console.log(O) // { a: 333 }
}());

如您所料,这个自调用匿名函数会抛出一个错误。不幸的是,在旧浏览器上,您不能依赖 polyfill,例如 https://github.com/kriskowal/es5-shim

事实上,Object 原型(prototype)上的seal 方法避免了'TypeError' 异常,但在调用时静默失败。
来自文档:

This should be fine unless you are depending on the safety and security provisions of this method, which you cannot possibly obtain in legacy engines.

关于Javascript Object.seal() 不会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20315906/

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