Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - setTimeout callback argument

Let's consider this piece of JavaScript:

function Person(name) {
    this.name = name;
}

Person.prototype.showName = function() {
    alert(this.name);
}


var mike = new Person("mike");
//mike.showName();  

window.name = "window"; 

I don't understand the difference between the behavior of

setTimeout(mike.showName(), 5000);

and

setTimeout(function(){
    mike.showName();
}, 5000);

Why is the behavior different? It really confuses me. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your question really has nothing at all to do with setTimeout. You simply need to understand the difference between a function call and a reference to a function.

Consider these four assignments:

var one = function() { mike.showName(); };
var two = mike.showName;
var three = mike.showName();
var four = (function() { mike.showName(); })();

The first two assign a reference to a function to their respective variables. The last two, however, call functions (that's what the parens are for) and assign their return values to the vars on the left-hand side.

How this relates to setTimeout:

The setTimeout function expects as its first argument a reference to a function, so either one or two above would be correct, but three and four would not. However, it is important to note that it is not, strictly speaking, a mistake to pass the return value of a function to setTimeout, although you'll frequently see that said.

This is perfectly fine, for example:

function makeTimeoutFunc(param) {
    return function() {
        // does something with param
    }
}

setTimeout(makeTimeoutFunc(), 5000);

It has nothing to do with how setTimeout receives a function as its argument, but that it does.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...