Skip to content Skip to sidebar Skip to footer

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.defi

Solution 1:

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;

Solution 2:

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

Post a Comment for "How Do I Redefine A Property From A Prototype?"