(0,function)(arg1,agr2,)
1 2 3
| (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);
|
example one
1 2 3 4 5 6 7 8
| (function() { (0,eval)("var foo = 123"); })(); console.log(foo); (function() { eval("var bar = 123"); })(); console.log(bar);
|
example two
when you want to call a method without passing the object as the this value:
1 2 3 4 5
| var obj = { method: function() { return this; } }; console.log(obj.method() === obj); console.log((0,obj.method)() === obj);
|
example three
depending on the context, it might be the arguments separator instead of a comma operator:
1 2 3 4 5 6
| console.log( function(a, b) { return function() { return a; }; } (0, function (arg) { })(this) );
|
In this scenario, (0, function (arg) { /* ... */ })
are the arguments (a=0, b=function (arg) { /* ... */ })
to the function
1 2 3
| function(a, b) { return function() { return a; }; }
|
rather than the comma operator. Then, the (this)
at the end is function call with argument this to the returned function function() { return a; }
.