javascriptthisprototypeprototype-chain

Why can't we access function via obj.prototype.function(), why prototype function can't access 'this'?


How 3 different calls are different from each other?

let Person=function(name){
    this.name=name;
};

Person.prototype.func=function(){
    console.log('Hey I am '+this.name);
};

let jay=new Person("jay");

jay.func(); /*This Works*/
jay.__proto__.func(); /*This doesn't have access to this.name? why?*/
jay.prototype.func(); /*This gives error, Why?*/


Solution

  • When you do

    jay.__proto__.func();
    

    you invoke the func function with a calling context of everything that came before the final dot: that is, with a this of jay.__proto__, which is the same object as Person.prototype:

    let Person=function(name){
        this.name=name;
    };
    Person.prototype.func=function(){
        console.log(this === Person.prototype);
        console.log(this === jay.__proto__);
    };
    let jay=new Person("jay");
    jay.__proto__.func();

    The name property is on the jay instance itself. It's not on the prototype, so referencing this.name inside the method when this is the prototype doesn't show the name property of the instance.

    You could also make the call work with the proper this if you use .call instead: jay.__proto__.func.call(jay);, which will call the function with the this set to jay not jay.__proto__.

    jay.prototype.func(); /This gives error, Why?/

    The .prototype property is a bit confusing. It only usually has meaning when it's a property of a function, in which case, created instances from that function have an internal prototype (or __proto__) of that prototype object.

    On normal instances and pretty much everywhere else, the .prototype property doesn't mean anything special and likely won't exist. So there's nothing that exists at jay.prototype.