0
var Person = function() {
    this.name = "Jay";
}

Person.prototype.getName = function() {
    return this.name;
}

var jay = new Person();
console.log(jay.getName()); // Jay
console.log(Person.prototype); // { getName: [Function] }

When I call new Person() I think it sets jay's internal [[prototype]] property as Person.prototype object. So I understand that when I try to access a property that doesn't exist like getName it will check the object's [[prototype]] which is Person.prototype for getName. Please correct me if I'm wrong.

What I'm confused about is how the Person.prototype object is able to access jay from this? From what I understand this refers to the object invoking the method, which is Person.prototype not jay, and this object doesn't hold name property.

petabyte
  • 1,487
  • 4
  • 15
  • 31
  • 1
    The following answer may be helpful in figuring out more about prototype, constructor functions and the value of this: http://stackoverflow.com/a/16063711/1641941 – HMR Jul 06 '14 at 12:15

1 Answers1

1

You're confusing "the place where the method is defined" with "the object performing the method." It is defined on Person.prototype, but the method is invoked on that particular object.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • Just to confirm, when the prototype chain finds `getName` will it do `jay.getName = Person.prototype.getName` before performing the method? Or use `call` method? Thanks – petabyte Jul 06 '14 at 07:24
  • @Jay: Neither, really. The prototype chain is used to look up the property in the first place, so there is no need to copy anything, and `call()` isn't necessary — but the effect is much the same as if you'd used `call` with the function. – Chuck Jul 06 '14 at 08:39