在这种特殊情况下,这似乎是多余的,但有时这种方法很有用。
例如,使用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
值传递时,它也很有用:
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