Reputation: 2257
As shown below, the method()
will output hello,undefined
. What is the scope of the method()
? Thank you.
var obj = {
name:'Tom',
sayHello:function() {
console.log("hello," + this.name);
}
}
obj.sayHello();
var method = obj.sayHello;
method();
output
hello,Tom
hello,undefined
Upvotes: 2
Views: 53
Reputation: 18354
The scope of method
is the global window
object
You'd have to do:
method.call(obj); //instead of method()
or
var method = obj.sayHello.bind(obj);
to achieve the same efect
Info for the call
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Info for the bind
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Cheers
Upvotes: 2
Reputation: 7811
obj.sayHello()
's scope is within obj
. method
is a global property, so assigning it to the sayHello
function makes the sayHello
function look for this.name
within the global scope.
To understand this, assign a global property of name directly in the script
var obj = {
name:'Tom',
sayHello:function() {
console.log("hello," + this.name);
}
}
obj.sayHello();
//Assign name to the global scope
this.name = "Jerry";
var method = obj.sayHello;
method.call(this); //Calling from the global scope, same as method()
//Then call method from the obj scope
method.call(obj);
Upvotes: 2
Reputation: 3618
var method
's scope is global. it is equals to just define a function
var method = function() {
console.log("hello," + this.name);
}
Upvotes: 1
Reputation: 164831
Because method
is part of the window
object, this
refers to window
.
Consider this example
var name = 'foo';
method();
logs...
> hello,foo
Upvotes: 3