Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  170] [ 7]  / answers: 1 / hits: 22961  / 11 Years ago, thu, july 18, 2013, 12:00:00

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

More From » javascript

 Answers
11

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

[#76917] Wednesday, July 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;