1

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

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

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

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

4

2 回答 2

3

如果您能够在要避免的代码之前运行代码,则可以尝试劫持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;
于 2015-01-29T15:44:56.673 回答
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);
于 2015-01-29T15:45:40.353 回答