Terrence Brannon
Terrence Brannon

Reputation: 4968

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._;

Upvotes: 2

Views: 108

Answers (1)

Toby Allen
Toby Allen

Reputation: 11211

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.

Upvotes: 1

Related Questions