给定一个对象 obj
,我如何断言其属性 prop
不可配置?
首先,我想我可以使用getOwnPropertyDescriptor
:
if(Object.getOwnPropertyDescriptor(obj, prop).configurable)
throw Error('The property is configurable');
但这并不是万无一失的,因为它可以被修改:
var getDescr = Object.getOwnPropertyDescriptor;
Object.getOwnPropertyDescriptor = function() {
var ret = getDescr.apply(this, arguments);
ret.configurable = false;
return ret;
};
有没有万无一失的方法?
最佳答案
假设obj
是native object (这对于 host objects 可能不可靠,请参阅 an example ),您可以使用 delete
operator .
当delete
与对象属性一起使用时,它返回调用[[Delete]]的结果内部方法。
如果属性可配置,[[Delete]] 将返回 true
。否则,它将在严格模式下抛出 TypeError
,或者在非严格模式下返回 false
。
因此,要断言 prop
是不可配置的,
在非严格模式下:
function assertNonConfigurable(obj, prop) { if(delete obj[prop]) throw Error('The property is configurable'); }
在严格模式下:
function assertNonConfigurable(obj, prop) { 'use strict'; try { delete obj[prop]; } catch (err) { return; } throw Error('The property is configurable'); }
当然,如果该属性是可配置的,那么它就会被删除。因此,您可以使用它来断言,但不能检查它是否可配置。
关于javascript - 断言属性不可配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29285761/