The JavaScript this statement
The this keyword refers to the object a function is being called on — but its value depends entirely on how the function is invoked, not where it's defined. In a method call it's the object; standalone it's undefined (strict mode); in an arrow function it's inherited from the surrounding scope. That last one is why arrows are great for callbacks.
Overview
this is the most misunderstood keyword in JavaScript, and the reason is that its value isn't fixed — it's decided at call time, by how the function is called. The same function can have a different this depending on context. Get this one rule and most of the confusion clears up: this is the object the function is invoked on.
The cases follow from that. In a method call, obj.greet(), this is obj. Called as a standalone function, greet(), this is undefined in strict mode (or the global object in sloppy mode). With new, this is the brand-new instance. In a DOM event handler added with addEventListener, this is the element. The classic bug is pulling a method off its object (passing it as a callback) so it loses its this.
This is exactly where arrow functions shine: an arrow has no this of its own and inherits it from the surrounding scope, so a callback written as an arrow keeps the this you expect. The older fixes still exist too: fn.bind(obj) returns a function permanently bound to a this, and fn.call(obj, ...) / fn.apply(obj, args) invoke it with a chosen this immediately.
Syntax
const user = {
name: "Ada",
greet() { return "Hi, " + this.name; } // this === user
};
user.greet(); // "Hi, Ada"
const fn = user.greet;
fn(); // this is undefined (strict) - the bug
user.greet.bind(user)(); // fix with bind
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const counter = {
count: 0,
inc() { this.count++; return this.count; }
};
const a = counter.inc(); // this === counter
const b = counter.inc();
document.getElementById('out').textContent =
'method calls: ' + a + ', ' + b + '\n' +
'count is now ' + counter.count; // 1, 2 / count is now 2
</script>
Best practices
- Remember
thisdepends on how a function is called, not where it's defined. - Use an arrow function for callbacks so they inherit the surrounding
this. - Use
bind()to lock a method'sthiswhen passing it as a callback. - Avoid relying on
thisin standalone functions — it'sundefinedin strict mode.
Frequently asked questions
What does this refer to in JavaScript?
new, or event handler.Why is this undefined in my function?
this is undefined in strict mode. Bind it, call it as a method, or use an arrow function.What is this in an arrow function?
this; they inherit it from the surrounding scope, which is why they're ideal for callbacks.What is the difference between call, apply and bind?
call and apply invoke a function immediately with a chosen this (call takes arguments separately, apply as an array); bind returns a new function permanently bound to that this.