1

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?

stackular
  • 1,431
  • 1
  • 19
  • 41

2 Answers2

3

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;
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    This is a *terrible* solution, but it is the only one I've found and it seems to work fine, so I'll go with it. – stackular Jan 30 '15 at 11:25
1

Have you tried something like this? It would have to run before new Test instances are created though.

var Test = function () {};

Object.defineProperties(Test.prototype, {
    p: {
        get: function () {
            return 5;
        }
    },

    a: {
        get: function () {
            return 5;
        }
    }
});

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

var t = new Test();

console.log(t.a, t.p);
plalx
  • 42,889
  • 6
  • 74
  • 90
  • This should work, and you could define the property as an argument of [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) rather than call `Object.defineProperty` afterwards. http://jsfiddle.net/Xotic750/j66peg0z/ – Xotic750 Jan 29 '15 at 15:59
  • @Xotic750 Yes, I was just too lazy not to copy/paste so once again I just copy/pasted yours ;) – plalx Jan 29 '15 at 16:35