javascript匿名函数语法 [英] javascript anonymous function syntax

查看:61
本文介绍了javascript匿名函数语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个块之间有什么区别?

What is the difference between the following two blocks?

// block 1
{
    console.log("anonymous block");
}

// block 2
(function anon() {
    console.log("anonymous block 2");
})();

我在Netbeans中运行了此程序(使用node.js插件),它们似乎都可以工作...

I ran this in Netbeans (using the node.js plugin) and they both seem to work...

推荐答案

不同之处在于,您可以使用后一种形式隐藏全局变量而不破坏它们.

The difference is that you can use the latter form to hide global variables without destroying them.

例如,假设您使用的是jQuery库,默认情况下该库将其主命名空间别名为$.如果您想将$用于其他目的,而又不更改通常使用$的方式,则可以执行以下操作:

For example, suppose you're using the jQuery library, which by default aliases its main namespace to $. If you wanted to use $ for a different purpose without changing how $ is normally used, you could do something like this:

(function($) {
    // Use $ without clashing with the jQuery object.
})(someObject);

实际上,它还可以用于其他目的.由于undefined在JavaScript中不是保留字,因此可以给它赋值并失去其用途.因此,您根本无法将值传递给undefined参数,并且您知道它会正常运行而不会与全局值冲突.

In fact, it's also useful for one other purpose. Since undefined is NOT a reserved word in JavaScript, it can be given a value and lose its purpose. So you could simply not pass a value into an undefined parameter, and you know it will behave properly without clashing with a global value.

undefined = "some not-undefined value";    // you'd have to be an idiot to do this but I've seen it done
(function(a, b, undefined) {
    console.log(typeof(undefined) === "undefined");   // true
})(someA, someB);

这篇关于javascript匿名函数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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