为什么函数用括号括起来? [英] Why is the function with in parenthesis?

查看:220
本文介绍了为什么函数用括号括起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

为什么函数包含在括号中?我已经从括号中取出了这个代码,它没有任何问题。

Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.

将代码放入(function(){...这里的代码...})();喜欢它在以下示例中?

What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?

代码:

(function() {
    "use strict";
    // Doesn't work because strict mode 
    // enforces the fact that the second example shouldn't work
    if (true) {
        function fn1() {
            // This won't run
            console.log("doesn't work -- have a great Die Hard Day XIII");
        };
        fn1();
    }
})();

代码这里:将JQuery字作为参数发送给这个命名空间的是什么。我知道函数包含在(...)中的原因是创建一个命名空间。我想一个更好的问题是为什么一个人会传入一个变量,但我想这将是另一个命名空间需要变量的情况。

Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.

( function( $ ) {
    // Init Skrollr
    var s = skrollr.init({
        render: function(data) {
            //Debugging - Log the current scroll position.
            //console.log(data.curTop);
        }
    });
} )( jQuery );


推荐答案


我采取了这个括号内的代码,没有问题。

I have taken this code out of parenthesis and it works with no trouble.

这不正确;它本身无法运行(甚至无法解析)。 JavaScript在函数声明所在的位置看到函数并假设它是函数声明。括号用于强制上下文成为表达式。如果它明确地是一个函数文字 - 例如,在变量声明中 - 但许多人发现它更具可读性,那么这种做法是多余的。例如,有一个 jsHint选项来强制执行

That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.

这篇关于为什么函数用括号括起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆