this is an identifier for values that is designed to support object oriented programming.
When a method or a constructor is invoked, the JavaScript interpreter binds this to a likely-focal object.
⚠ Warning ⚠
Resources on the internet regarding this are often inconsistent, and frequently misrepresent the truth.
What this isn’t
Consider the following snippet:
var fn = function (a, b) {
console.log(this);
}this is not bound to:
- the function object in which
thisappears - an instance of the function in which
thisappears - an object that has the function in which
thisappears as a property (method) - an object literal that has the function in which
thisappears - an execution context or scope of the function call in which
thisappears
this is bound to:
- the object to the left of the dot where the containing function is called.
For example:
1
2
3
4
5
6
7
var obj = {
fn: function (a, b) {
console.log(this);
}
};
obj.fn(3, 4);
In the statement obj.fn(3, 4) on line 7, since obj is to the left of the dot, this is bound to obj.
The operative determiner of which object this refers to depends only on the function invocation, and not with that function’s membership as a property of any other objects.
Behavior of the this keyword
The rules for how this gets a binding mostly resemble the rules for how positional function parameters get bindings.
If we want to call a method with an object that does not have the function as a property, we can use Function.prototype.call() using the following syntax:
fn.call(thisArg, ...args);.call() can also be used to override this when the function is already being invoked as a method of another object.
obj.fn.call(anotherObj, ...args); // `this` binds to anotherObjHow to determine what this is bound to
| Binding Pattern | Binding Target | Use Case |
|---|---|---|
| Global Reference | The global object (window in a browser) |
The default choice (when not use strict) |
| Free Function Invocation | The global object (window in a browser) |
The default choice |
.call or .apply Invocation |
First argument (thisArg) |
Manually specifies a binding for this |
Construction Mode (new) |
A new object created for the invocation | So constructors will operate on the instance they create |
| Method Invocation | object on the left of the call time dot | So methods run in the context of the object calling them |
Most of the time, it’s Method Invocation. Look to the left of the dot.