Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by (0, somefunc)(args) [duplicate]

I've been going through some of gmails javascript (writing an extension) and I've seen (0, _.ab)(a), or variations, all over the places. What does this achieve?

I've tried some tests such as

function a(a,b,c){ console.dir(a+b+c); }
(0, a)(1,2,3)

However I can't work out why they wouldn't just call a(1,2,3) directly. Does calling it using (0,a) have some odd benefit?

I've made a jsperf (http://jsperf.com/direct-vs-0-func-calls) to test this, and a(1) vs (0,a)(1) seem identical.

Edit: As Far as I can make out google only use it where they need to directly call a function, such as if ((0, _.wa)(a)) (taken from gmail's source)

like image 253
Joey Ciechanowicz Avatar asked Jan 24 '14 14:01

Joey Ciechanowicz


1 Answers

The (0, func)() syntax ensures that the context (this) in the called function func is the global context.

For example:

var myContext = {
    func: function () { 
        console.log(this);
    }
};

myContext.func();        // => myContext
(0, myContext.func)();   // => window
like image 186
Alon Gubkin Avatar answered Sep 24 '22 01:09

Alon Gubkin