Search code examples
javascriptprototype

Cannot Access Getter Method on __proto__


I was learing prototypes in Javascript and got a lot about their usages. But I'm confused about the following that how it didn't work.

function Employee(name)
{
    this.name = name;
}

Employee.prototype.code = "SIMPLE";
Employee.prototype.getName = function()
{
    return this.name;
}

var a = new Employee("Manish");
var b = new Employee("Vikash");

a.__proto__.code // SIMPLE
a.__proto__.getName() // Undefined

Why we can't access a function on __proto__ while a.__proto__ == Employee.prototype returns true.


Solution

  • You can access the function on the __proto__ object like you expect - but you're getting this behavior because you lose the binding to this when you call it this way so the function is not returning what you expect. The value of this is determed by the calling context. For the purpose of experimenting, you can try adding the binding back like this:

    a.__proto__.getName.bind(a)()
    // Manish
    // or
    a.__proto__.getName.call(b)
    // Vikash