Due to implicit binding we know when we call a method of any object by using dot Operator, same like
// Example: one
const obj = {
name: 'Toseef',
getName() {
return this.name
}
}
obj.getName()
"THIS" operator targets the calling object which is on left of the dot, it fine and understandable, and we also know when we call inner nested method without call or bind, "THIS" only target the most left sided object of the dot, same like
// Example: two
const obj = {
name: 'Toseef',
nested: {
getName() {
return this.name
}
}
}
obj.nested.getName() // will return undefined, because nested don't have name.
In this case "THIS" will return undefined, RIGHT.! But my Question is when we call a method of Object and that method is not avail in object directly, so then it go to prototype object to find our required method.! lets see Example
// Example: Three
Person.prototype.getName = function() {
return this.name;
}
function Person(name, age) {
this.name = name;
this.age =age;
}
const p = new Person("toseef", 21);
p.getName() // will return "toseef" but why
As we can see we are calling getName method in p object which has nested object called prototype. because every constructor function has method prototype.
mean it will look like p.prototype.getName(), but we know without call or bind "THIS" only targets most left sided object, so why p.prototype.getName() is returning value instead of undefined, because nested object dont have name.!!!
// Example: Three
Person.prototype.getName = function() {
return this.name;
}
function Person(name, age) {
this.name = name;
this. Age =age;
}
const p = new Person("toseef", 21);
p.getName() // will return "toseef" but why
According to me p.prototype.getName() should be return undefined, because "THIS" is targeting prototype object instead of p and prototype don't have name. Please let me understand why "THIS" is targeting p instead of prototype.!!!