41
var ninja = (function(){
    function Ninja(){};
    return new Ninja();
})();

Why is the function above encapsulated in parentheses and why is there a (); at the end?

I think it's a constructor function because of the (); at the end, but why is the object wrapped in parentheses?

4

4 回答 4

15

这段代码相当于:

function Ninja() {
    // nothing here
}

var ninja = new Ninja();

尽管在您列出的代码中,函数/对象 Ninja 不是全局范围。

该代码(function() {...})();基本上说“获取此处包含的任何函数并立即执行它”。所以它正在创建一个匿名函数并在之后立即调用它。

于 2013-08-09T20:08:28.647 回答
7

It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this keyword would change meaning, e.g. in

var someClass = function() {
    this.property = something;
    this.update = (function(obj) {
        function() {
            $('.el').each(function() {
                $(this).html( obj.property );
            });
        };
    )(this);
};

While I want to refer to this.property inside the $('.el').each(), this changes meaning within that scope and refers to the current DOM element that is being looped through with .each(). So by passing this as a parameter into the IIFE (and calling that parameter obj) I can use obj.property to refer to what is this.property when outside the scope of $('.el').each( ..., function() { ... });.

Let me know if that makes sense or if you have any questions :)

于 2013-08-09T20:08:28.693 回答
1

为什么函数声明封装在'('s中,以及为什么最后有'();'

它同时声明和执行函数。

您可能会看到:揭秘命名函数表达式 - Juriy "kangax" Zaytsev

于 2013-08-09T20:06:59.190 回答
0

建议:参考 Benalman

立即调用函数表达式 (IIFE) 幸运的是,SyntaxError “修复”很简单。告诉解析器期待一个函数表达式的最广泛接受的方法就是用括号括起来,因为在 JavaScript 中,括号不能包含语句。此时,当解析器遇到 function 关键字时,它知道将其解析为函数表达式而不是函数声明。

// Either of the following two patterns can be used to immediately invoke
// a function expression, utilizing the function's execution context to
// create "privacy."


(function(){ /* code */ }()); // Crockford recommends this one

(function(){ /* code */ })(); // But this one works just as well
于 2013-08-09T20:11:30.303 回答