1

Given an object obj, how can I assert that its property prop is not configurable?

First, I thought I could use getOwnPropertyDescriptor:

if(Object.getOwnPropertyDescriptor(obj, prop).configurable)
    throw Error('The property is configurable');

But that isn't foolproof, because it could have been modified:

var getDescr = Object.getOwnPropertyDescriptor;
Object.getOwnPropertyDescriptor = function() {
    var ret = getDescr.apply(this, arguments);
    ret.configurable = false;
    return ret;
};

Is there a foolproof way?

Oriol
  • 274,082
  • 63
  • 437
  • 513

1 Answers1

1

Assuming that obj is a native object (this may be unreliable for host objects, see an example), you can use the delete operator.

When delete is used with an object property, it returns the result of calling the [[Delete]] internal method.

And [[Delete]] will return true if the property is configurable. Otherwise, it will throw a TypeError in strict mode, or will return false in non-strict mode.

Therefore, to assert that prop is non-configurable,

  • In non-strict mode:

    function assertNonConfigurable(obj, prop) {
        if(delete obj[prop])
            throw Error('The property is configurable');
    }
    
  • In strict mode:

    function assertNonConfigurable(obj, prop) {
        'use strict';
        try {
            delete obj[prop];
        } catch (err) {
            return;
        }
        throw Error('The property is configurable');
    }
    

Of course, if the property is configurable, it will be deleted. Therefore, you can use this to assert, but not to check whether it is configurable or not.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513