The value of this
depends on which context it appears:
- Function: The value of
this
will depend on how a function was called. The value of this
is not always the object that
has the function as an own property, but the object that is used to call the function. The methods Function.prototype.call()
,
Function.prototype.apply()
, or Reflect.apply()
can be used to explicitly set the value of this
. Is it also
possible to create a new function with a specific value of this that doesn’t change regardless of how the function is called with
Function.prototype.bind()
. In non-strict mode, this
will always be an object and will default to globalThis
if set to undefined
or null
.
- Arrow function: The value of
this
will be the same as the enclosing context. Arrow functions will not create a new
this
binding. When invoking arrow functions using call()
, bind()
, or apply()
, the
thisArg
parameter is ignored.
- Class: Class methods behave like methods in other objects: the
this
value is the object that the method was accessed on. If the
method is not transferred to another object, this
is generally an instance of the class. However, for static methods, the value of
this
is the class instead of the instance.
- Global: outside of any functions or classes (also inside blocks or arrow functions defined in the global scope), the value of
this
depends on what execution context the script runs in.
When a function is called without an explicit object context, the this
keyword refers to the global object. This also applies when it
is used outside of an object or function. The global this
object refers to the global context in which the JavaScript code is executed.
This can cause problems when the code is executed in different contexts, such as in a browser or in a Node.js environment, where the global object is
different. Such uses could confuse maintainers as the actual value depends on the execution context, and it can be unclear what object the
this
keyword is referring to.
In JavaScript’s "strict mode", using this
in the global context will always be undefined
.
this.foo = 1; // Noncompliant: 'this' refers to global 'this'
console.log(this.foo); // Noncompliant: 'this' refers to global 'this'
function MyObj() {
this.foo = 1; // Compliant
}
MyObj.func1 = function() {
if (this.foo === 1) { // Compliant
// ...
}
}
Instead, simply drop the this
, or replace it with globalThis
. The globalThis
global property gives access to
the global object regardless of the current environment.
foo = 1;
console.log(foo);
function MyObj() {
this.foo = 1;
}
MyObj.func1 = function() {
if (this.foo === 1) {
// ...
}
}