0

Why this.name is not working here?how to fix that?

var john = {
  name: 'John',
  greet: function(person) {
    alert("Hi " + person + ", my name is " + this.name);
  }
};
var fx = john.greet;
fx("Mark"); //Hi Mark, my name is
Tyler Roper
  • 20,529
  • 6
  • 30
  • 51
nirmesh
  • 111
  • 6
  • I'm no longer able to answer this because it was closed, but in my opinion, the best answer is to **use a `getter` that returns a function**. You don't need to apply contexts, or use global vars, etc. See here: http://jsfiddle.net/j6y9c0bx/ – Tyler Roper Dec 14 '18 at 04:19

2 Answers2

3

this refers to the JavaScript window object in this case, because you are actually redefining the function name. Calling john.greet ("Mark") directly would work, because this would be referring to the object which the method is called on.

In your case, you can use the object name to refer to it's properties.

See this post for reference: How does the "this" keyword in Javascript act within an object literal?

Another possible solution is to change the context of the function itself, which can be done by using the Function.prototype.bind() method. For details, refer to @Markus Stefanko's answer.

var john = {
  name: 'John',
  greet: function(person) {
    alert("Hi " + person + ", my name is " + john.name);
  }
};
var fx = john.greet;
fx("Mark"); //Hi Mark, my name is
NikxDa
  • 3,777
  • 1
  • 22
  • 43
1

You can solve this by binding the this context of fx like so :

var fx = john.greet.bind(john);

This way you're explicitly stating that fx will work with john as this context. Before that you're relying on the implementation to pick the context for you.

( For example your original code works when running as a snippet, but won't work in a browser context. )

Markus Stefanko
  • 1,812
  • 1
  • 4
  • 14