如何从原型中重新定义属性?

时间:2015-01-29 15:29:30

标签: javascript defineproperty

如何从对象的原型中删除属性p

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

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

这会产生 TypeError:无法重新定义属性:p 。有没有办法可以删除属性并重新添加它?或者是否可以在创建属性后设置configurable属性?

2 个答案:

答案 0 :(得分:2)

如果您能够在要避免的代码之前运行代码,可以尝试劫持Object.defineProperty以防止添加该属性:

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

或者你可以让它可配置,以便以后能够修改它:

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

最后,您可以恢复原始文件:

Object.defineProperty = _defineProperty;

答案 1 :(得分:1)

你尝试过这样的事吗?它必须在创建新的Test实例之前运行。

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