(0, someFunction)() 在javascript中的含义是什么[重复]

2023-12-22

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

(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);

我发现它总是返回括号中的最后一项。

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


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

例如,与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

当您想要调用方法而不将对象作为对象传递时,它也很有用this value:

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

另请注意,根据上下文,它可能是参数分隔符而不是逗号运算符:

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

在这种情况下,(0, function (arg) { /* ... */ })是参数 (a=0, b=function (arg) { /* ... */ }) 到函数

function(a, b) {
  return function() { return a; };
}

而不是逗号运算符。 (然后,(this)最后是带参数的函数调用this到返回的函数function() { return a; }。但这部分与逗号运算符/参数分隔符差异无关)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

(0, someFunction)() 在javascript中的含义是什么[重复] 的相关文章

随机推荐