Search code examples
javascriptdefineproperty

How do I redefine a property from a prototype?


How do I remove the property p from the object's prototype?

var Test = function() {};
Object.defineProperty(Test.prototype, 'p', {
  get: function () { return 5; }
});

Object.defineProperty(Test.prototype, 'p', {
  get: function () { return 10; }
});

This produces TypeError: Cannot redefine property: p. Is there a way I can remove the property and re-add it? Or is it possible to set the configurable attribute after the property was created?


Solution

  • If you are able to run code before the code you want to avoid, you can try hijacking Object.defineProperty to prevent adding that property:

    var _defineProperty = Object.defineProperty;
    Object.defineProperty = function(obj, prop, descriptor) {
        if(obj != Test.prototype || prop != 'p')
            _defineProperty(obj, prop, descriptor);
        return obj;
    };
    

    Or you can make it configurable, to be able to modify it later:

    var _defineProperty = Object.defineProperty;
    Object.defineProperty = function(obj, prop, descriptor) {
        if(obj == Test.prototype && prop == 'p')
            descriptor.configurable = true;
        return _defineProperty(obj, prop, descriptor);
    };
    

    At the end, you can restore the original one:

    Object.defineProperty = _defineProperty;