Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the greet function not return the expected value?

Tags:

javascript

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");
like image 737
flylib Avatar asked Jul 18 '13 02:07

flylib


3 Answers

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;
}
like image 158
Matthew Graves Avatar answered Oct 17 '22 01:10

Matthew Graves


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
like image 30
RobG Avatar answered Oct 17 '22 03:10

RobG


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.

like image 1
Sean Halls Avatar answered Oct 17 '22 01:10

Sean Halls