user3293653
user3293653

Reputation:

Why does underscore use `root` instead of `this`?

In some cases, I see aliases to reduce the look-up chain, but in this case it is a simple one line alias with no reduction.

var root = this;

I think this is more descriptive as it will point to window in the browser or a multitude of different global variables if JavaScript is running on the server side.

If it had to be aliased I feel like

var global = this;

would be more descriptive.

Why is the word root used? I've heard root used in the context of a "root user", but in the context of JavaScript development, I don't get it.

Upvotes: 4

Views: 397

Answers (3)

mpm
mpm

Reputation: 20155

it uses root in the noConflict function

 _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

here this refers to underscore and root to the global scope.

as for root instead of global,it's a matter of opinion

Upvotes: 0

Bergi
Bergi

Reputation: 664599

In some cases, I see aliases to reduces the look-up chain, but in this case it is a simple one line alias with no reduction.

It has a little advantage in minification. root can be minified to a single letter, multiple uses of this cannot. See also Is me = this in JavaScript a good practice to support minification?.

Also, the root variable is closed over in the _.noConflict: function

_.noConflict = function() {
    root._ = previousUnderscore;
    return this;
};

Without root, it would need to be rewritten as

_.noConflict = function() {
    this._ = previousUnderscore;
    return _;
}.bind(this);

If it had to be aliased I feel like var global = this; would be more descriptive. Why is the word root used?

Yeah, global would've been fine as well - only that it might add confusion since global is the idenfier used in Node for this object. root does stand for "root scope" or "root object" here.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

The meaning of this can change in closures.

function doSomething() {
    function helper() {
        alert(this); // I'm helping!
    }

    alert(this);
    helper();
}
someElement.onclick = doSomething;

While you might expect two alerts showing the same, the second one will actually refer to the global object instead (or null in strict mode, I think).

Doing var root = this; means that you have something that can reliably be called on, that won't change unexpectedly.

The name root... well, it's just a name.

Upvotes: 3

Related Questions