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
setTimeouttakes 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
setTimeoutworks 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.