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’
is not assigned a value until an object invokes the function where ‘this’ is defined.
when we use this
in a global function, it refers to (and has the value of) the global window object
The value of this
is completely irrelevant to __proto__
. It is set exactly to the object before the dot.
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.
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
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
setTimeout() moves the function out into a global context.
// test object
// window object
Share your insights in the comments below.
, Digital Web