自动执行功能 [英] Self-executing functions

查看:114
本文介绍了自动执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

(function(){})()之间的区别;和function(){}();

我想了解一个JavaScript的一些功能稍微好一些。在 The Definitive JavaScript 中,它表示自执行函数应该有括号围绕它们:

I am trying to understand a few of the features of JavaScript a little better. In The Definitive JavaScript it says that self-executing functions should have brackets round them like so:

var obj = (function() {
    var value = 0;

    return {
        increment: function(inc) {
            value += typeof inc === "number" ? inc : 1;
        },
        getValue: function() {
            return value;
        }
    }
})();

但在 JavaScript - 好零件其中这个例子取自它,它有上面的自执行函数,没有括号轮,如下所示:

but in JavaScript - The Good Parts where this example is taken from, it has the above self-executing function without the brackets round, like so:

var obj = function() {
    var value = 0;

    return {
        increment: function(inc) {
            value += typeof inc === "number" ? inc : 1;
        },
        getValue: function() {
            return value;
        }
    }
}();

这两个例子都适用于我,但我想询问功能是否存在任何差异我应该知道。我希望这不是太微不足道。我只是想确定。

Both of these examples work for me, but I wanted to ask if there were any differences in functionality that I should be aware of. I hope this isn't too trivial. I just wanted to be sure.

非常感谢。

编辑

正如Rob W指出的那样,这个主题还有另一个主题。 这是一个关于此问题的优秀博客来自另一篇文章。

As Rob W has pointed out, there is another thread on the subject. This is an excellent blog regarding this issue that was linked to from the other post.

推荐答案

在这种情况下没有任何区别,但只有 因为它的前缀是:

There isn't any difference in this case, but only because it's prefixed with:

var obj = ...

没有它,只有第一个版本是正确的,因为你需要额外的括号来允许解释器正确地解析函数作为函数表达式而不是函数声明

Without that, only the first version is correct, because you need the additional parentheses to allow the interpreter to correctly parse the function as a function expression and not as a function declaration.

您当然只会省略 var obj 如果你只希望函数运行(即你想要它的副作用)但是它不返回任何值,或者你不关心它的返回值是什么。

You would of course only omit var obj if you only want the function to run (i.e. you want its side effects) but it either returns no value, or you don't care what its return value is.

这篇关于自动执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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