JavaScript this Keyword
this is a special variable that every regular function gets automatically. It refers to the object the function is working on — but which object that is depends on how the function is called, not where it's defined. That makes this one of the most confusing parts of JavaScript, so let's go through the rules one at a time.
The rules at a glance
| How the function is called | this is |
|---|---|
As a method: obj.method() |
obj (the object before the dot) |
As a plain function: fn() |
undefined in strict mode (global object in sloppy mode) |
With new: new Fn() |
the newly created object |
With call/apply/bind |
whatever object you pass |
| Arrow function | inherited from the surrounding code |
Event handler el.addEventListener(…, function) |
the element |
| At the top level of a module | undefined |
Method calls
When a function is called as object.method(), this is the object to the left of the dot:
const account = {
owner: "Rosa",
balance: 120,
deposit(amount) {
this.balance += amount;
return `${this.owner} now has ${this.balance}`;
},
};
console.log(account.deposit(30));
const other = { owner: "Tim", balance: 5, deposit: account.deposit };
console.log(other.deposit(10)); // same function, different `this`Rosa now has 150
Tim now has 15
The same function gave different results because this was decided at call time.
Losing this
If you take a method out of its object and call it on its own, the "object before the dot" is gone. In strict mode (modules, classes) this becomes undefined:
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
},
};
const inc = counter.increment; // just the function, detached
try {
inc();
} catch (err) {
console.log(err.message);
}Cannot read properties of undefined (reading 'count')
This happens a lot when passing methods as callbacks, e.g. setTimeout(counter.increment, 100) or button.addEventListener("click", obj.handle).
Fixing it: bind, call and apply
These function methods set this explicitly:
fn.call(obj, a, b)— call now withthis = objand arguments listed.fn.apply(obj, [a, b])— same, but arguments as an array.fn.bind(obj)— returns a new function permanently bound toobj.
function introduce(greeting, punctuation) {
return `${greeting}, I'm ${this.name}${punctuation}`;
}
const ada = { name: "Ada" };
const alan = { name: "Alan" };
console.log(introduce.call(ada, "Hello", "!"));
console.log(introduce.apply(alan, ["Hi", "."]));
const counter = {
count: 0,
increment() {
return ++this.count;
},
};
const boundInc = counter.increment.bind(counter);
boundInc();
console.log(boundInc());Hello, I'm Ada!
Hi, I'm Alan.
2
Arrow functions don't have their own this
An arrow function uses the this of the code around it — wherever it was written. That's exactly what you want for callbacks inside methods:
const team = {
name: "Rockets",
members: ["Lia", "Sam"],
listWithArrow() {
return this.members.map((m) => `${m} plays for ${this.name}`);
},
listWithFunction() {
return this.members.map(function (m) {
return `${m} plays for ${this?.name}`; // `this` is undefined here
});
},
};
console.log(team.listWithArrow());
console.log(team.listWithFunction());[ 'Lia plays for Rockets', 'Sam plays for Rockets' ]
[ 'Lia plays for undefined', 'Sam plays for undefined' ]
But the flip side: don't use an arrow function as an object method — it won't get the object as this.
this in classes and constructors
With new, this is the brand-new object being built. In class methods it's the instance the method was called on:
class Timer {
constructor(label) {
this.label = label;
this.ticks = 0;
}
tick() {
this.ticks++;
return `${this.label}: ${this.ticks}`;
}
}
const t = new Timer("egg");
t.tick();
console.log(t.tick());
console.log(this); // top level of a moduleegg: 2
undefined
this in event handlers
In a DOM event listener written with a regular function, this is the element the listener is attached to (the same as event.currentTarget). With an arrow function it's the outer this:
<button id="btn">Click me</button>
<script>
document.getElementById("btn").addEventListener("click", function () {
this.textContent = "Clicked (this = " + this.tagName + ")";
});
</script>Tip: If
thisconfuses you in a callback, check how the function is called. The fix is almost always an arrow function, or.bind(obj).
Test yourself
In user.greet(), what is this inside greet (a regular function)?
- The global object
- user
- greet
- undefined
What does fn.bind(obj) return?
- The result of calling fn
- A new function with this fixed to obj
- obj
- undefined
Where does an arrow function get its this from?
- The object before the dot
- The caller
- The surrounding (enclosing) scope
- It is always undefined