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

How do I redefine a property from a prototype?

如何从对象的原型中删除 属性 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 属性?

如果您能够 运行 在您想要避免的代码之前编码,您可以尝试劫持 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;

你试过这样的事情吗?在创建新的 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);