flylib flylib - 3 months ago 87
Javascript Question

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");

Answer

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;
}
Comments