简体   繁体   中英

Why does the greet function not return the expected value?

Question:

Why does the greet function not return the expected value?

Code:

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

Person.prototype.greet = function(otherName){
     return "Hi" + otherName + ", my name is " + name;
}

How do I answer this? I create a new person then what do I do?

var John = new Person("John");

Wrong access method. the variable name isn't defined, only this.name is defined. So it's looking for a variable in the function scope called name instead of a property of the object called name .

To access an object's property from within the object we use the this keyword. Thus we'll need to use this.name to access the name property in the implementation below.

Person.prototype.greet = function(otherName){
     return "Hi" + otherName + ", my name is " + this.name;
}

In your code:

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

When called as a constructor, the above will create a named property of an instance called name and assign it the value of the name parameter.

> Person.prototype.greet = function(otherName){
>     return "Hi" + otherName + ", my name is " + name;
> }

Here the identifier name is used as a variable, but the identifier you are looking for is a named property of the instance, so you need to access it at as such. Typically, this function will be called as a method of the instance so this within the function will be a reference to the instance. So you want:

      return "Hi" + otherName + ", my name is " + this.name;

So now when you can do (note that variables starting with a capital letter are, by convention, reserved for construtors):

> var john = new Person("John");

and then:

john.greet('Fred');

because greet is called as a method of john , it will return:

Hi Fred, my name is John

Alternatively, since this is an issue of scope inheritance (second function not having access to the variable "name"), we can rephrase the code to look like this to include it all under the Person function:

function Person(name){
   this.name = name;
   this.greet = function(otherName){
      return "Hi" + otherName + ", my name is " + name;
    }
}

Works as well.

You need to change the greet function to use the object's name with the this keyword:

Person.prototype.greet = function(otherName){
     return "Hi" + otherName + ", my name is " + this.name;
}

after that, just call John.greet("other name");

Try the following:

function Person(name){
   this.name = name;
   this.greet = function(otherName){
      return "Hi " + otherName + ", my name is " + name;
    }
} 

Person("Joe")
greet("Kate")

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