Understanding the different contexts of this
in Javascript is an important step towards truly understanding the language. In addition to its importance, it's also something that has been written about to death.
If you're using Javascript, and don't fully understand how the this
keyword in javascript works, here are some great articles that will give you the understanding you need.
this
Resources
A brief overview of different "this" scenarios, from a good general Javascript overview called "Javascript Garden"
http://bonsaiden.github.io/JavaScript-Garden/#function.this
A longer, but still higher level overview
http://davidshariff.com/blog/javascript-this-keyword/
Another long-form explanation, with some additional technical detail
http://unschooled.org/2012/03/understanding-javascript-this/
And a step by step, in-depth article
http://www.2ality.com/2014/05/this.html
Checking your understanding
If you think you understand this
, make sure you understand why each of the following work the way they do. If the examples make sense, you probably have a pretty decent understanding! If after those articles you still don't fully understand, leave a comment or contact me for more explanation.
var global = 'global example'; function globalExample() { return this.global; } console.log(this.global); //outputs 'global example' console.log(globalExample()); //outputs 'global example' var obj = { global: 'obj example', example: globalExample }; console.log(obj.global); //outputs 'obj example' console.log(obj.example()); //outputs 'obj example' var obj2 = { global: 'obj2 example' }; console.log(globalExample.call(this)); // outputs 'global example' console.log(globalExample.call(obj)); // outputs 'obj example' console.log(globalExample.call(obj2)); // outputs 'obj2 example'