Reputation: 84
I'm trying to look over random libraries' source code to get the gist of creating my own library and I'm stumbled at the beginning of Underscore's source code, which reads like this:
// Baseline setup
// --------------
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
My questions are:
1) What's the purpose of the expression for the root variable? I see that it's trying to see if there is a window object. But what is the global object, since it's undefined on the browser?
2) What is the purpose of creating separate variables for native methods that are easily accessible without storing them unnecessarily as variables?
3) What's the purpose of the Symbol prototype in terms of underscore? Never seen it used like this before.
Anyway, thanks for any help clearing this up for me.
Upvotes: 2
Views: 89
Reputation: 5742
1) In node.js
, global
is the equivalent to browser's window
, and as its stated in the comment, this
in some VMs. This is for the library to behave the same cross-platform.
2) Apparently ArrayProto
and ObjectProto
are used a lot in the codebase so it seems convenient to have a shorter reference.
3) Here you can read the pull request, apparently there was a problem with _.isEqual
and symbols
Upvotes: 1