When a property is enabled, the prototype chain goes through, as you probably know. But if you have an awesome object and try to evaluate awesome.doStuff , then awesome.prototype will never be requested for the property. You can check this in your example, "doStuff" in awesome => false , but "doStuff" in awesome.prototype => true .
So what you are doing is not changing the implicit properties of awesome , you are changing its prototype, that is, any objects created when new awesome executed will have this property. Check: "doStuff" in new awesome() => true . And that makes sense, since using f/awesome it is not possible to distinguish between a constructor or a regular function.
The procedure for resolving the property p object o looks like this:
- Check if
p defined on o - Check if
p exists on o.__proto__ (using __proto__ is non-standard but widely implemented, except that jscript is last checked and now it's deprecated in SpiderMonkey) - Check if
p defined on o.constructor.prototype - Check if
p exists on o.constructor.prototype.prototype - etc.
So one solution would be to simply set o.__proto__ = AwesomeClass.prototype . Think of __proto__ as a hidden intermediate object between the object and its prototype. Each instance gets its own unique __proto__ object. But this is outdated and non-standard, as I said.
We could also set the values ββin Function.prototype , but this could override other Function properties and affect all instances of Function. We do not want this.
So what's left? Not so much. It is not possible to establish a complete prototype of an object while retaining its inherited prototype. You will need to iterate over the prototype and copy all the properties. Fortunately, this will allow instanceof to behave as expected when working with the goals of the constructors, as well as properly inherit / override properties.
The problem is that there is no built-in way to copy the properties of an object to another and there is no standard way to change the prototype chain of an ad-hoc object ( __proto__ ).
So use __proto__ , or iterate through a prototype.
source share