The ‘this’ Keyword
The this keyword in JavaScript is a special idetifier that references the
context in which the code is executing1.
Its behavior can vary depending on whether the code is running in strict mode or not2.
- In non-strict mode this always should refer to an object. If this is
undefinedornull,thisgets substituted withglobalThis. - If this points to any other primitive value, that value will be wrapped in the corresponding object.
Global This
Outside of any function, this refers to globalThis, which is undefined in
strict mode or the 'global object' in non-strict mode. In code running at a
top-level of a module this is always 'undefined' because modules always run in
strict mode3.
Inside regular functions
For regular functions, this is always defined at the time of invocation:
- For standalone function calls,
thisrefers toglobalThis(as mentioned earlier:undefinedfor strict mode and global object for non-strict).
'use strict';
function showThis() {
console.log(this);
}
showThis(); // undefined
- For calling as a method
thispoints to the related object (i.e. the object preceding the dot)
function showThis() {
console.log(this);
}
const obj1 = {
a: 1,
showThis,
};
obj1.showThis(); // { a: 1, showThis: [Function: showThis] }
obj1['showThis'](); // Different syntax, same result
- When a function is calling as a callback this can refers to
undefinedor other value, depends of the API. For example, when a callback passed toaddEventListener()is invoked,thisusually refers to the DOM element that triggered the event.
function showThis() {
console.log(this);
}
setTimeout(showThis);
// Depends on the Host. E. g.:
// in browser: Window object
// in node: Timeout object
- In constrictors, if function is invoked with the
newkeyword,thiswill refer to newly created object. Its internal [[Prototype]] property set to theprototypepropery of the constructor function.
function ShowThis() {
this.a = 1;
console.log(this);
}
new ShowThis(); // ShowThis {a: 1}
- When using the methods
.bind(),.apply()and.call()., these can explicitly redefinethisby passing its value as an argument.
'use strict';
function showThis() {
console.log(this);
}
showThis.apply(1); // 1
Inside arrow function
Arrow functions don't have their own this. They inherit it from that lexical environment, where they were defined (not called!). It works the same way as closure.
'use strict';
const showThis = () => {
console.log(this);
};
const obj1 = {
a: 1,
showThis,
};
obj1.showThis(); // undefined