创建后分配对象原型

Assigning an object prototype after creation

我在网上搜索有关原型继承的所有示例和问题都显示了将原型分配给 构造函数 以及在调用之前,很像以下代码:

Object.beget = function (o) {
    var F = function () {};
    F.prototype = o;
    return new F();
};

我的问题是,有没有办法在 对象不是构造函数)原型在实例化后更改它这样我就可以访问新的原型方法而无需直接调用它,或者换句话说,对象继承它的新原型方法?

编辑:

我想问题的重点可能不清楚,我对增强对象的原型不感兴趣,我真正想要的是一种分配新原型的方法,而不会改变具有相同原型的其他对象第一个.

您可以为原始对象 o 分配新属性,新对象实例将自动访问这些属性:

Object.beget = function (o) {
    var F = function () {};
    F.prototype = o;
    return new F();
};

var o = {
    a: 1
};

var instance = Object.beget(o);

instance.a === o.a; // true

o.b = function () {};

instance.b === o.b; // true

如果在对象创建后关联的原型发生变化(这意味着应该删除所有来自先前原型链的属性并添加新属性),这不等于创建了一个实例这个新原型的新对象?在这种情况下,为什么不创建一个新对象并使用它呢?

如果我遗漏了任何用例,请告诉我。

Is there a way to change an object's prototype after it has been instatiated?

是的,有:Object.setPrototypeOf (ES6 only), the counterpart of Object.getPrototypeOf - which access an object's real prototype, not just the .prototype property. There is also the .__proto__ getter/setter property (deprecated) that does the same (see Quick Javascript inheritance: Understanding __proto__).

但是,请注意,这样做通常是一个糟糕的主意。不仅因为可能有engines that don't support these, but it defeats all the fancy optimisations an engine uses of instances: Why is mutating the [[prototype]] of an object bad for performance?.