When I add a property to Function.prototype, why does it disappear from the chain?
Why is the property yyy (which is in the property chain) undefined?
function Shape() { }
Shape.prototype.xxx = 111;
Function.prototype.yyy = 222;
let x = new Shape;
console.log(x.xxx) // 111
console.log(x.yyy) // undefined???
Function.prototype is only on the prototype chain of functions, so it's not in the prototype chain of your x object, because that isn't a function. (And yes, this is a bit confusing.)
The prototype property of a function X is used to set the prototype of an object created via new X or Object.create(X).
Your Shape.prototype's prototype is Object.prototype, not Function.prototype. (Function.prototype is the prototype of Shape, the function.)
Your code creates two prototype chains, one for the function Shape and one for Shape.prototype (and x):
+−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−−−−−+
| Shape | +−−−>| Function.prototype |
+−−−−−−−−−−−−−−−| | +−−−−−−−−−−−−−−−−−−−−+
| [[Prototype]] |−−−+ | [[Prototype]] |−−−+
| prototype |−−−+ | yyy: 222 | |
+−−−−−−−−−−−−−−−+ | +−−−−−−−−−−−−−−−−−−−−+ |
| \ +−−−−−−−−−−−−−−−−−−−−+
\ +−−−−−−−−−−−−−−−−−−−−+ +−−>| Object.prototype |
+−>| Shape.prototype | / +−−−−−−−−−−−−−−−−−−−−+
/ +−−−−−−−−−−−−−−−−−−−−+ |
| | [[Prototype]] |−−−+
| | xxx: 111 |
| +−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−+ |
| x | |
+−−−−−−−−−−−−−−−+ |
| [[Prototype]] |−−−+
+−−−−−−−−−−−−−−−+
As you can see, since Function.prototype isn't in x's chain, x.yyy is undefined. But Shape.yyy is, since Shape inherits from Function.prototype:
function Shape() { }
Shape.prototype.xxx = 111;
Function.prototype.yyy = 222;
let x = new Shape;
console.log(x.xxx); // 111
console.log(x.yyy); // undefined
console.log(Shape.yyy); // 222
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With