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