0

How to call below function and my expected output is "Hi John, my name is James"

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

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

name is not defined in above code.

2 Answers2

2

Use this.name

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

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

var p = new Person("Foo");
console.log(p.greet("Bar"));   // "Hi Bar, my name is Foo"
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
2

to access the properties attached on the this object, well.. you have to call this.

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

Person.prototype.greet = function(otherName){
  return "Hi " + otherName + ", my name is " + this.name;
}
Bamieh
  • 10,358
  • 4
  • 31
  • 52