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

查看:34
本文介绍了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天全站免登陆