开发者

How to properly self-execute a closure

I'm studying closures and the global scope, and am confused about when to use }()) vs. })(). It seems that I've lucked upon a situation where it doesn't matter which one I use.

(function() {

    var myFunction = 开发者_JAVA百科(function() {
        var i=100;
        return function() {
            return i++;
        }
    }());
    var X = myFunction();
    console.log(X);
    X = myFunction();
    console.log(X);

})();


Its how expressions work in JS.

The following all work because the +,-,(,~... designate the beginning of an expression.

!function(){}()
~function(){}()
+function(){}()
-function(){}()
(function(){})()
(function(){}())


(function () { return 1; }); doesn't evaluate the function. ("append" + " us") does evaluate the strings.

So yeah, in this case it doesn't matter because:

var myFunction = (function() {
    var i=100;
    return function() {
        return i++;
    }
}());

evaluates to (function() { return i++; } which just returns the anonymous function.

and:

var myFunction = (function() {
  var i=100;
    return function() {
      return i++;
    }
})();

evaluates myFunction after the braces. And.. just returns the anonymous function. Woh.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜