As I dive into learning about prototypes in JavaScript and the prototype chain, a particular issue has me puzzled. Consider this constructor:
function Circle() {
this.radius = 1;
}
let c1 = new Circle();
Circle.prototype.toString = function() {
console.log('The radius is: ' + this.radius);
}
c1.toString(); // "The radius is: 1"
In the scenario above, both c1
and Circle
point to the same object in memory for their prototype. The toString
function is defined on the prototype, not within the constructor. So, when toString
is called on c1
, the Javascript engine first looks at c1
then up towards the prototype object that contains the toString
function. It's traversing "up" the prototype chain.
The question arises - why does this.radius
work? How does the toString
function, defined on the prototype, access instance members defined in the constructor? Essentially, it seems like the function is looking "down" the prototype chain from the prototype object to the actual instance object.