WTF is this?

The this statement – an elusive concept to grasp. So what does it do? When can you use it and why would you even want to?

 

Global Context – via MDN

console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true


this.a = 37;
console.log(window.a); // 37

 

 

What is this?

this is a JavaScript keyword typically used in functions and event handling. this takes the value of the object passed to the function that’s being called. In short, if you do not have a function with an object or value passed into it, the this keyword will not be available to you to edit that function. Instead, this will refer to a global variable (what?)

 

What does this refer to?

this refers to data that’s passed into the parent of this. As an object-oriented keyword, this starts out as a child of the global window object.

How do I make it refer to what I want to refer it to?

this is already an available reference for functions, and should only be used for that.

Check to see what this refers to by using

console.log(this);

If you’re wanting to use this inside of an inner function/closure (function within a function), this reference will be different than in the parent. One common way to pass this reference is to ‘bind’ this to the original reference

this.handleSearchTermChange = this.handleSearchTermChange.bind(this)

MDN – bind() – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

 

When should I use this?

Use this to help make changes to the original function’s object. Whatever has been pulled into the function is the object that will be edited.

Why would I want to use this, instead of directly writing what is being referred?

This is an extremely useful shortcut, that not only helps with code readability but also allows you to access an object with much greater ease than typing out the reference each time.

 

When should I not use this?

Don’t use this if you’re not sure what it refers to.

 

Most important things to know about this:

This is an extremely powerful keyword that an easier work environment to an object passed to a function

 

Further Reading:

MDN – this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

JavaScript is Sexy – Mastering this http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

QuirksMode – http://www.quirksmode.org/js/this.html

Leave a Reply

Your email address will not be published. Required fields are marked *