In the code below, I think the way the prototypal chain works (basically) is that if a child object (mike, in this case) doesn't have a method itself, it looks up the prototype chain, via __ proto__, to see if a parent object has it within its prototype object, and if it does, then 'mike' should have access to it. Right?
If that's right, just about, why is 'farewell' is not available to mike? Obviously I can see it's the 'this.' (or lack thereof) that's making the difference, but if __ proto__ allows a child object to access the methods in the prototype objects of parents, why do we need to bother with this. at all??
Thanks very much!
function PersonConstructor() {
this.greet = function sayHello() {
console.log("hello");
};
farewell = function sayBye() {
console.log("Bye");
};
}
function personFromConstructor(name, age) {
const person = new PersonConstructor();
person.name = name;
person.age = age;
return person;
}
const mike = personFromConstructor("Mike", 30);
console.log(mike.greet); // [Function: sayHello]
console.log(mike.farewell); // undefined
This doesn't have much to do with prototypes at all. What happens when you do new PersonConstructor()
is, simplified:
let obj = {};
/* [ here be dragons and details about setting up prototype chains ] */
PersonConstructor.call(obj); // `this` inside PersonConstructor is obj
return obj;
Essentially, it's equivalent to:
let obj = {};
obj.greet = function sayHello() {
console.log("hello");
};
farewell = function sayBye() {
console.log("Bye");
};
And that should illustrate why farewell
is not ending up as part of the object in any way.