使用JavaScript/Node.js,如果对象在冻结后被修改,是否可能抛出错误?我想把一个不可变的属性放在一个对象上,同时防止对象被重新赋值。
在本例中,我正在编写一个库,并且我需要赋值module.exports = x;是不可变的。
我想防止用户向x添加属性,以及防止module.exports被重新分配。不仅如此,如果用户尝试上面的操作,我想抛出一个错误,而不是无声的错误,这是可能的吗?
发布于 2016-05-14 06:18:19
如果用户代码在严格模式下运行,它将自动抛出错误。
function log(obj) {
document.querySelector('pre').innerText += JSON.stringify(obj, null, 2) + '\n';
}
function nonStrict(obj) {
obj.b = 2;
log(obj);
}
function strict(obj) {
'use strict';
try {
obj.b = 2;
} catch(e) {
log(e.message);
}
}
var obj = {
a: 1
};
Object.freeze(obj);
nonStrict(obj);
strict(obj);<pre></pre>
发布于 2016-05-14 06:32:01
您可以使用Object.freeze(x);。
例如在模块foo.js中
var foo = {id: 42};
Object.freeze(foo);
module.exports = foo;在模块bar.js中,您会得到错误。
'use strict';
var foo = require('./foo');
foo.bar = 42; // TypeError: Can't add property bar, object is not extensible请注意,要抛出错误,您需要使用严格模式。如果您不使用它,对象将继续是不可变的,但它只是不会抛出错误。
https://stackoverflow.com/questions/37220093
复制相似问题