Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototype chain fails to retrieve a property set in Function.prototype

Tags:

javascript

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???
like image 818
DuduArbel Avatar asked Jun 07 '26 21:06

DuduArbel


1 Answers

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
like image 104
T.J. Crowder Avatar answered Jun 10 '26 09:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!