In most object-oriented programming languages, the keyword ‘this’ has a special meaning. Usually it refers to the object being the execution context (i.e. to the current instance of the object). For example, we use this when referring to an object property from within: we type this.propertyName, and then the context is the object and this refers to it.
‘this’in JavaScript
In JavaScript it is more complicated because where this refers to depends not only on how the function is defined but also on the form of calling it.
Take a look how this works depending on invocation place and form.
Global context
Used in a global context bound to the global object, like window in a web browser.
this; // window
Inside object method
Used inside of an object method bound to the closest enclosing object. The object is the new context of the this keyword. Note that you should not change function () to ES6 syntax fun: () => this.context because it will change the context.
Used inside a function that has no context (has no object as parent) bound to the global context, even if the function is definded inside the object.
Note that we use var context instead of let/const context because let and const change the variable enclosed context. var is always closest to the global execution context. let and const declare variables only in a local block scope.
var context = "global";
const obj = {
context: "object",
funA: function() {
function funB() {
const context = "function";
return this.context;
}
return funB(); // invoked without context
}
};
obj.funA(); // global
Inside constructor function
Used inside a function that is the constructor of the new object bound to it.
var context = "global";
function Obj() {
this.context = "Obj context";
}
const obj = new Obj();
obj.context; // Obj context
Inside function defined on prototype chain
Used inside a function defined on the prototype chain to creating an object bound to it.
call() and apply() are JavaScript functions. With these, an object can use methods belonging to another object. call() takes arguments separately where apply() takes them as an array.
this is here bound to new context changed in call() and apply() methods.