最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

closures - Self-Invoking Functions in JavaScript - Stack Overflow

programmeradmin4浏览0评论

What's the difference between these functions? Thanks for reply!

Function #1

var myQuery = (function() {

  (...)

})();

Function #2

var myQuery = (function() {

  (...)

});

What's the difference between these functions? Thanks for reply!

Function #1

var myQuery = (function() {

  (...)

})();

Function #2

var myQuery = (function() {

  (...)

});
Share Improve this question asked Oct 27, 2010 at 16:45 Randy HartmanecRandy Hartmanec 1291 silver badge4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 9

In the first case, you're self-invoking a function literal and assigning the value of the invocation to the variable myQuery.

In the second case, you're assigning a reference to the anonymous function that you've defined. Here, myQuery acts like a pointer or a reference to a function.

To better illustrate this.

var myQuery = (function() {
   return "Hello";
})();

In this case, myQuery contains the value Hello. Now if you had:

var myQuery = (function() {
   return "Hello";
});

myQuery contains a reference to the function. If you used console.log in Firebug to output this value, you would see function(). This reference is something you can pass around or even invoke. So:

var myQuery = (function() {
   return "Hello";
});

var value = myQuery();

Now, value will contain Hello. Hope this explains the difference.

I'll simplify Function #2 and perhaps that will better show the differences.

var myQuery = function(){ (...) };

In Function #2, you're saying "Assign myQuery a reference to this function." In Function #1, you're saying "Assign myQuery the value of a call to this function."

The first one is a self-invoking function, called with an empty parameter list. The value of myQuery will be what this function returns.

The second one is simple assignment of an anonymous function. There is no invocation in this one.

well the first function executes as the line is passed and the second will have to be executed to get the value

Eg : http://jsfiddle/yVrwX/

发布评论

评论列表(0)

  1. 暂无评论