【问题标题】:Assert that a property is not configurable断言属性不可配置
【发布时间】:2015-03-26 18:06:12
【问题描述】:

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

有没有万无一失的方法?

【问题讨论】:

    标签: javascript object properties assert


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多