Understanding ‘this’ in Javascript

We need a way of identifying and referring to the object that we’re currently working with. When we execute a function, it gets a ‘this’ property, where ‘this’ points to the object which invokes the function. In the following example, ‘this.age’ would point to age property of ‘person’ object. Another snippet from jquery: The reason ‘this’ is bound to the button object is because the jQuery library binds ‘this’ to the object that invokes the click method.

Facts about ‘this’

this is not assigned a value until an object invokes the function where ‘this’ is defined. // TODO when we use this in a global function, it refers to (and has the value of) the global window object // TODO The value of this is completely irrelevant to __proto__. It is set exactly to the object before the dot. // TODO

Different behaviours of ‘this’

Using ‘this’ inside a function

Since function is running in context of global object, it would point to global object. In case of script running in browser, it would be pointing to ‘window’ object.

Using ‘this’ inside a callback


Using ‘this’ within a closure

‘this’ inside the anonymous function cannot access the outer function’s ‘this’, so it is bound to the global window object, when strict mode it is undefined. we use a common practice in JavaScript and set the this value to another variable before we enter the forEach

Using ‘this’ in a function assigned to a variable

We can fix this problem by specifically setting the this value with the bind method:
var showUserData = user.showData.bind (user);
Using ‘this’ while assigning methods between objects So this would not work:
gameController.avgScore = appController.avg(); // null would be assigned
Instead use:
appController.avg.apply (gameController, gameController.scores);
console.log (gameController.avgScore);     // 46.4​
Another example for ‘this’ value required to be set is as follows: Bind function can help fix ‘this’ value as follows:
test.getAge = test.getAge.bind(person);
test.getAge();     // 18 

Using setTimeout()

setTimeout() moves the function out into a global context. Prints
// test object
// window object
Share your insights in the comments below. References: Javascript is sexy, Digital Web