断言属性不可配置

Assert that a property is not configurable

本文关键字:配置 属性 断言      更新时间:2023-09-26

给定一个对象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是本机对象(这对于主机对象来说可能不可靠,请参阅示例),则可以使用delete运算符。

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');
    }
    

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