Why does underscore use `root` instead of `this`?
javascript, underscore.js
Solution
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.
Problem
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.