断言属性不可配置

时间:2015-03-26 18:06:13

标签: javascript object properties assert

给定一个对象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;
};

有一种万无一失的方式吗?

1 个答案:

答案 0 :(得分:1)

假设objnative objecthost 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');
    }
    

当然,如果属性是可配置的,它将被删除。因此,您可以使用它来断言,但不能检查它是否可配置。