var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + this.name;
}
}
//person.welcome();
// output is
// Hi John
// I was expecting output to be
// Hi Mary
person.welcome.call();
// output is
// Hi Mike
// In this case since no argument is passed to call so this is window and
// I get that window.name is Mike
views:
58answers:
4Why were you expecting Hi Mary in the first case?
var name = 'Mary';
Doesn't overwrite this.name, but rather creates a local variable named name in the function.
In the second case, you are using call, which takes a this argument, and:
Determines the value of this inside fun. If thisArg is null or undefined, this will be the global object.
var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + this.name;
}
}
this.name refers to the object property "name"
name refers to the variable "name"
You would get the expected result with return 'Hi ' + name;
If you are waiting the output to be Hi Mary then you do not need to use this in the welcome function
This should do it
var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + name;
}
}
When you do person.welcome() the this keyword references person, so on the welcome function this.name would become person.name which is John.
this always refer to the object you are calling the function from. In most simple cases this would be whatever is in front of the .. For example, in the case of person.welcome() this now refers to person. If you call person.welcome.call() this refers to the window, because you did not specify anything as a parameter to call().