Frage

I just opened Retina.js in hopes of learning a few things, but I'm stumped on the first line.

var root = (typeof exports === 'undefined' ? window : exports);

What exactly does this line do?

Further down,

 function Retina() {}

 root.Retina = Retina;

How was the Retina property set out of root without defining it first?

War es hilfreich?

Lösung

typeof is an operator that, when used on a variable that’s not defined at all, will still result in the value 'undefined'. So the expression:

(typeof exports === 'undefined' ? window : exports)

checks whether exports isn’t in scope. If it isn’t, it results in window (the global object in browsers), and if it is, it results in exports (a standard name for exporting things from [sort of] modules – see Relation between CommonJS, AMD and RequireJS?). The result is then assigned to root.

In case you were wondering about the conditional operator,

var d = a ? b : c;

is more or less equivalent to

var d;

if (a) {
    d = b;
} else {
    d = c;
}

As for root.Retina = Retina;, like with every other property in JavaScript, there’s no need to declare it and there is no facility to declare it.

Andere Tipps

If the type of exports equals 'undefined', then we set it to window. Otherwise, we set it to exports.

Its ternary, you could do it this way :

if(typeof(exports) === 'undefined') 
root = window;
else 
root = exports
var root = (typeof exports === 'undefined' ? window : exports);

This line checks if exports is not undefined. In Node.js environment, exports special variable refers to the current module. So, if exports is not defined, you are in a browser otherwise Node.js environment.

So, if you are in a browser, root will refer window object otherwise, the current module object(exports). root.Retina assigns the Retina function to either the window or the current module.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top