All examples and questions I've came upon searching on the web about prototypal inheritance shows the assigning of prototypes to constructor functions and before it's called, much like the following code:
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
My question is, is there a way to change an object (not a constructor function) prototype after it has been instatiated in such a way that I can access the new prototype methods without calling it directly, or in other words, in such a way where the object inherits its new prototype methods?
EDIT:
I guess the focus of the question might not be clear, I am not interested in enhancing an object's prototype, what I really want is a way to assign a new prototype, without altering other objects which had the same prototype as the first.
Is there a way to change an object's prototype after it has been instatiated?
Yes, there is: 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__).
However, please notice that it is usually a terrible idea to do that. Not only because there may be 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?.