相关疑难解决方法(0)

为什么需要在同一行上调用匿名函数?

我正在阅读一些关于闭包的帖子,到处都看到了这个,但是没有明确的解释它是如何工作的 - 每次我被告知要使用它......:

// Create a new anonymous function, to use as a wrapper
(function(){
    // The variable that would, normally, be global
    var msg = "Thanks for visiting!";

    // Binding a new function to a global object
    window.onunload = function(){
        // Which uses the 'hidden' variable
        alert( msg );
    };
// Close off the anonymous function and execute it
})();
Run Code Online (Sandbox Code Playgroud)

好的,我看到我们将创建新的匿名函数,然后执行它.所以在那之后这个简单的代码应该工作(并且确实如此):

(function (msg){alert(msg)})('SO');
Run Code Online (Sandbox Code Playgroud)

我的问题是这里发生了什么样的魔术?当我写作时我想:

(function (msg){alert(msg)})
Run Code Online (Sandbox Code Playgroud)

然后会创建一个新的未命名函数,如函数""(msg)...

但那么为什么这不起作用?

(function (msg){alert(msg)});
('SO');
Run Code Online (Sandbox Code Playgroud)

为什么它需要在同一行?

你能指点一些帖子或给我解释一下吗?

javascript anonymous-function iife

372
推荐指数
8
解决办法
29万
查看次数

JSON键是否必须用引号括起来?

示例:以下代码是否对JSON规范有效?

{
    precision: "zip"
}
Run Code Online (Sandbox Code Playgroud)

或者我应该总是使用以下语法?(如果是这样,为什么?)

{
    "precision": "zip"
}
Run Code Online (Sandbox Code Playgroud)

我在JSON规范中没有真正发现这个问题.虽然他们在示例中使用了键周围的引号.

json specifications standards-compliance

217
推荐指数
5
解决办法
7万
查看次数