With the following:
function Person() {
this.name = "john";
this.getName = function() {
return this.name;
};
}
var me = new Person();
Why would a proceeding:
setTimeout(function(){alert(me.getName())}, 3000);
returns john
while a proceeding:
setTimeout(me.getName(), 3000);
create a
Uncaught TypeError: Object [object DOMWindow] has no method 'getName'
The problem is that setTimeout
takes a function as the first argument.
In your code snippet:
setTimeout(function(){alert(me.getName())}, 3000);
You are passing in a function as the first argument which is then evaluated to do the alert.
In the second snippet you're passing in the result of invoking the function so this:
setTimeout(me.getName(), 3000);
Becomes this:
setTimeout('john', 3000);
Because of the way setTimeout
works it will allow you to pass in a string as the first argument that the runtime will attempt to invoke as a function resulting in an error.
Are you sure this is the code you used? setTimeout(me.getName(), 3000)
calls me.getName
and then passes the result as the first argument of setTimeout
.
If you meant setTimeout(me.getName, 3000)
it's because the function isn't bound to me
, so setTimeout
executes it in the context of the window
(where would it get me
from? You only passed the function itself).
Instead of putting the call inside an anonymous function, you could use bind:
setTimeout (me.getName.bind (me), 3000);
This isn't available in older browsers, but the MDN page has a fallback implementation.
You tagged the question with the correct answer: closures. When you are wrapping the code in an anonymous function, you create a closure which captures the value of the local variable called me.
As James pointed out the part of the question that doesn't work is a little weird.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.