Request Dev Services »

theDevTip.com

Pertaining to using ‘.this’ in JavaScript (Tip)

Should you use the “this” object, or is that unnecessary and redundant?

Consistently using ‘this‘ for object reference; while not particularly always required is a great idea in my opinion. It will ultimately help avoid any confusion and ambiguity when the time comes when you  expand or scale your code,  you begin nesting objects, creating more global or outer-functions, and doing things like callback functions.

If there’s no current object, ‘this’ refers to the next global object. In a web browser, that’s likely ‘window’ — the top-level object which represents the document, location, history and a few other useful properties and methods. But it could vary depending on your current code and any other global objects defined.

It’s usage is even more transparent when writing a function referencing an object.

Por ejemplo:

window.CoolWindowObj = "I'm the window object";

function RunThis() {
   alert(this.CoolWindowObj); // I'm the window object
   alert(window === this); // true
}

RunThis();

Some higher perspective in Execution contexts; The object that this refers to is basically redetermined every time control shifts into a new execution context and then remains fixed until control shifts to yet another different context. The value of this is typically dependent on two things: The type of code being executed (i.e., global, function, or eval) and then the caller of that code.

So,this refers to the global object in all global code. Since all programs start by executing global code, and this is fixed inside of a given execution context, we know that, by default, this is the global object.

Essentially, I do recommend consistently using ‘this’, although there may be some instances (especially early on while your code or project is small) to skip it. You will eventually inevitably want it to avoid ambiguity or confusion down the line, so using ‘this’ is certainly a best practice.

References:

Buckler, C. (2011, February 25). What is ‘this’ in JavaScript? — SitePoint. Retrieved December 22, 2017, from https://www.sitepoint.com/what-is-this-in-javascript/

Bergson-Shilcock, N. (n.d.). Unschooled. Retrieved December 22, 2017, from http://unschooled.org/2012/03/understanding-javascript-this/

 

P.S. Merry Christmas!

About the Author
Cameron Cashwell Web Developer
I build websites, web apps, and software. Wanna work together? Let's chat about your project!

Leave a Reply

avatar
  Subscribe  
Notify of