javascriptthis

why would you assign this to another variable?


At the start of the source code for underscore.js, you see this:

var root = this;

var previousUnderscore = root._;

So the question becomes why didnt the author just write:

var previousUnderscore = this._;

Solution

  • Two reasons,

    1. Readability, it makes it clearer what the code is doing, what it is referencing. this is very opaque.
    2. depending on context, this can refer to lots and lots and lots of differnt objects, root may be used in multiple place and will always refer to the correct object.