简体   繁体   中英

How does the 'prototype' object have access to the newly created object for 'this'?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM