MDN has a huge scary warning about modifying the prototype in your code:
Changing the
[[Prototype]]
of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in theObject.setPrototypeOf(...)
statement, but may extend to any code that has access to any object whose[[Prototype]]
has been altered. If you care about performance you should avoid setting the[[Prototype]]
of an object. Instead, create a new object with the desired[[Prototype]]
usingObject.create()
.
I’m wondering if there are any situations where you can modify an object’s prototype without causing cascading optimization effects that kill your program's performance. It seems like there should be. For example if you only modify the prototype right after the object is created (and before its used by anything else). But I imagine this is very engine-dependent.
So does anyone know if there are efficient ways to modify an object’s prototype?
Edit: The motivation for this question comes from a desire to create objects that actually inherit from Function
. And the only way I know how to do that is by modifying the prototype of a function. See the very bottom of Raynos’s answer here: javascript class inherit from Function class