这个代码(0,函数)在javascript中是什么意思 [英] What is the meaning of this code (0, function) in javascript

查看:115
本文介绍了这个代码(0,函数)在javascript中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某人的代码中找到了这段代码,听起来像这样:

I found this code in someone's code, it sound like this:

(0, function (arg) { ... })(this)

在我尝试如下玩之后,

(0, function (arg) { console.log(arg) })(2);
console.log((0, 1, 2, 3));
(0, function plus1 (arg) { console.log(arg + 1) }, function plus2 (arg) { console.log(arg + 2) })(5);

我发现它总会返回最后一项支架。

I found that it will always return last item in the bracket.

我想知道这个编程模式的名称是什么以及用例是什么?

I wonder what is the name of this programming pattern and what is the use case?

推荐答案

在这种特殊情况下,它似乎是多余的,但有时这种方法很有用。

In this particular case it seems superfluous, but sometimes this approach is useful.

例如,使用 eval

(function() {
  (0,eval)("var foo = 123"); // indirect call to eval, creates global variable
})();
console.log(foo);            // 123
(function() {
  eval("var bar = 123");     // direct call to eval, creates local variable
})();
console.log(bar);            // ReferenceError

当你想调用一个方法时它也很有用没有将对象作为这个值传递:

It's also useful when you want to call a method without passing the object as the this value:

var obj = {
  method: function() { return this; }
};
console.log(obj.method() === obj);     // true
console.log((0,obj.method)() === obj); // false

另请注意,视具体情况而定,可能是参数分隔符而不是逗号运算符:

Also note that, depending on the context, it might be the arguments separator instead of a comma operator:

console.log(
  function(a, b) {
    return function() { return a; };
  }
  (0, function (arg) { /* ... */ })(this)
); // 0

这篇关于这个代码(0,函数)在javascript中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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