2

Looking at cssnano source code, I came across this line

var proc = (0, _postcss2.default)();

From what I've tested, it seems to do the same thing as

var proc = _postcss2.default();

Why did cssnano assign proc using the first syntax?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Jeow Li Huan
  • 3,758
  • 1
  • 34
  • 52

1 Answers1

6

There is a subtle difference, in that the this value is different in default based on the two different calls. Consider the following code:

var _postcss2 = {
    default: function() {
        return this;
    }
};

var proc = (0, _postcss2.default)();
console.log(proc); // proc === window (or undefined in strict mode)

var proc = _postcss2.default();
console.log(proc); // proc === _postcss2

_postcss2.default() calls default as a method of the _postcss2 object and sets this accordingly, but (0, _postcss2.default)(); does not, and this would be window in non-strict-mode, and undefined in strict-mode.

The way the comma operator works, is that all the expressions are executed, but only the final expression is returned, so 0, is a short meaningless expression to use the comma operator to get the function reference itself, without setting it to a variable first.

If that makes a difference in this particular case, I cannot say without looking at the code itself.

The corresponding line from the source code for this code is, let proc = postcss();, with postcss being an ES6 import. This particular code is being generated by an ES6 transpiler, probably Babel.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • 1
    Good answer, although it raises the question of why the `default` method would use `this` if it's not intended to be called that way. – Barmar May 14 '16 at 06:21
  • You might want to add something about what the comma operator does, and why that changes things when the function call is made. – nnnnnn May 14 '16 at 06:25
  • @Barmar Yeah, the only thing I can think of is a hackish way of accessing the global `this` in both browsers and Node without `typeof`. Not something I would do though, I put everything in strict mode. – Alexander O'Mara May 14 '16 at 06:25
  • @nnnnnn Good call, I've added a short overview. – Alexander O'Mara May 14 '16 at 06:29
  • @Barmar Turns out it's something what I presume is Babel is generating for ES6 imports. Not sure exactly why though. – Alexander O'Mara May 14 '16 at 06:43