this
A special keyword that refers to whatever object is currently 'in charge' of the running code.
What is it?
Code in a function sometimes needs to refer to "the object I belong to" without naming it, so the same code works for many objects. The keyword this refers to that object.
The tricky part: this doesn't depend on where a function is written, but on how it's called. Call the same function a different way and you can get a different this.
Explain like I'm 10
Think of "this" like the word "I" in a sentence. The word never changes, but who "I" means depends on who's speaking.
Examples
`this` depends on how a function is called
const user = {
name: "Amara",
greet() {
console.log("Hi, I'm " + this.name);
},
};
user.greet(); // "Hi, I'm Amara" — this = user, because user.greet() called it
const greetFn = user.greet;
greetFn(); // "Hi, I'm undefined" — this is no longer "user" hereCalling user.greet() sets this to user. Detach the function and call it on its own, and this no longer points to user.
Arrow functions and `this`
const user = {
name: "Amara",
greet: () => {
console.log("Hi, I'm " + this.name); // ❌ arrow functions don't have their own "this"
},
};Arrow functions deliberately have no this of their own. They use this from the code around where they were written, which usually isn't what you want for object methods.
How it works
For a regular function, JavaScript picks this based on how it's called:
obj.method()setsthistoobj.- A plain call,
fn(), setsthistoundefined(in strict mode) or the global object. .call(),.apply()and.bind()setthisexplicitly.
Arrow functions skip all this and borrow this from the enclosing scope.
Why does it exist?
this lets one method definition work for many objects. A single greet method can be shared by every user object, each referring to itself, instead of a hardcoded copy per object.
When to use it
Think about this whenever you write an object method, use a class, or pass a function as a callback. Knowing what this will be tells you whether the code works when it's called.
When not to use it
Functions that don't depend on an object's data often don't need this; a regular parameter is clearer. For object methods used as callbacks, use an arrow function or .bind() instead of trusting the caller to keep this right.
Common mistakes
Passing an object method as a callback (e.g. to
setTimeout) and losing its intendedthis.Using a regular function for an object method that's called as a plain callback, instead of binding it or using an arrow function.
Assuming
thisrefers to where a function is defined rather than how it's called.
Practice exercises
- Easy:
Create an object with a method that logs
this.name, and call it normally to confirm it works. - Medium:
Detach that method into its own variable, call it directly, and explain why
thisbreaks. - Hard:
Fix the broken example using
.bind(), and explain what.bind()actually does.
Interview questions
What determines the value of `this` inside a regular function?
How the function is called, not where it was defined. obj.method() sets this to obj. A standalone fn() gives a different this. new fn() and .call/.apply/.bind each set it differently again.
What does `this` become when a regular function is called completely standalone, like `fn()`, with no object in front of it?
In strict mode, undefined. In non-strict ('sloppy') mode, the global object (window in a browser). Strict mode changed this partly because accidental access to the global object is rarely wanted.
What is `this` set to inside a method called as `obj.method()`?
obj: the object directly left of the dot at the moment of the call.
Where does an arrow function get its `this` from?
It has no this of its own. It uses the this of the surrounding (lexical) scope where it was written, and that never changes, however the arrow function is called later.
If you copy a method off an object into a plain variable and call it from there, what happens to `this`?
The link to the object is lost. Calling the copy standalone follows the standalone rule (undefined in strict mode, otherwise the global object), not the object it came from.
What does `fn.call(thisValue, arg1, arg2)` do?
It calls fn immediately with this set to thisValue for that one call, passing arg1, arg2, ... as separate arguments.
How does `.apply()` differ from `.call()`?
Both call the function immediately with an explicit this. .apply() takes the arguments as one array (or array-like); .call() takes them as a comma-separated list.
What does `.bind()` do, and when is the `this` you pass to it actually locked in — immediately, or only once the bound function is finally called?
It returns a new function with this permanently fixed to the value you passed. The binding happens immediately, when .bind() is called, not later when the new function runs.
Once a function has been bound with `.bind()`, can a later `.call()` or `.apply()` on the resulting function override its `this`?
No. A bound function's this is locked. Any this passed through a later .call()/.apply() is ignored.
What happens to a bound function's `this` if it's called with `new` instead of as a plain function?
new wins. It ignores the bound this and creates a fresh object for this, like calling the original function with new. Any pre-supplied bound arguments are still used.
What's the actual priority order JavaScript uses when several of these rules could apply at once — `new`, explicit binding (`call`/`apply`/`bind`), an object method call, and the plain default?
Highest to lowest: new; then explicit this from call/apply/bind; then implicit this from a method call (obj.method()); and finally the default (undefined in strict mode, otherwise the global object).
If you pass an object's method directly to `setTimeout(obj.method, 1000)` instead of wrapping it, what is `this` when it eventually runs?
Not obj. setTimeout calls the function standalone, so this is the default (undefined in strict mode). It's the same problem as detaching any method into a variable and calling it later.
What are two idiomatic ways to fix a callback that's losing its intended `this`?
Wrap it in an arrow function at the call site, setTimeout(() => obj.method(), 1000), so it's still called as a method. Or bind it once, setTimeout(obj.method.bind(obj), 1000), which locks this however it's called.
If a plain (non-arrow) function is defined inside an object's method and called from inside that method, does it inherit the method's `this`?
No. A plain nested function called on its own gets its own default this, unrelated to the method's this. It's a classic, easy-to-miss gotcha. An arrow function in the same spot would inherit the method's this.
Inside a DOM event handler written as a regular function, what does `this` refer to?
The element the listener was attached to. The browser calls the handler as if it were a method on that element, effectively element.handler(event).
If that same event handler is written as an arrow function instead, does `this` still refer to the element?
No. An arrow function ignores the element this the browser supplies and uses the this from where it was written, which usually isn't the element.
If a class method is passed around as a callback (e.g. `<button onClick={instance.method}>`) without binding it first, what typically goes wrong?
It loses its link to instance like any detached method. When it's later called as a plain callback, this isn't instance, so code using this.someProperty breaks.
How does the "class field arrow function" pattern (`method = () => { ... }` instead of `method() { ... }`) fix the lost-`this` callback problem?
It's an arrow function, so it captures this from where it's defined: the constructor scope, where this is the new instance. It's assigned per instance (not shared on the prototype), so each instance gets its own already-bound version that's safe to pass as a callback.
What is `this` set to inside a constructor function invoked with `new`?
The new object that new is building. Assignments like this.name = name add properties directly to that instance.
What does `this` refer to inside a `static` method of a class?
The class (constructor function) itself, not an instance, since static methods are called on the class, like MyClass.staticMethod().
What does `this` refer to inside a getter or setter defined in a class?
The instance it's accessed through, just like this in a regular instance method, so the accessor can read or change that instance's data.
Does `this` behave any differently inside a generator function's body compared to a regular method?
No. A generator method follows the same call-site rules for this as any method. Being a generator only changes how it produces values (with yield).
What is `this` at the very top level of an ES module, outside any function?
undefined. In a classic script, top-level this is the global object, but modules are implicitly strict mode and have no ambient global this.
Does writing `"use strict"` change what `this` is inside a method call like `obj.method()`?
No. It only changes the standalone-call case. In obj.method(), this is obj either way. Strict mode changes a plain fn() call's fallback from the global object to undefined.
Why did some older codebases write `const self = this;` at the top of a method, before arrow functions were common?
So a nested plain function (which would get its own this) could reach the outer method's this through the closed-over self variable. It was a manual workaround for the problem arrow functions later solved by inheriting this lexically.
Predict the output: `function show() { console.log(this.id); } const a = { id: 1, show }; const b = { id: 2 }; show.call(b);`
2. .call(b) sets this to b for that call. It doesn't matter that show is also a.show, because it's called through .call, not through a.
Predict the output: `function sum(a, b) { return this.multiplier * (a + b); } console.log(sum.apply({ multiplier: 10 }, [2, 3]));`
50. .apply() sets this to { multiplier: 10 } and spreads [2, 3] into a and b, giving 10 * (2 + 3).
Predict the output: `function greet(greeting) { console.log(greeting + ", " + this.name); } const hi = greet.bind({ name: "Amara" }, "Hi"); hi();`
"Hi, Amara". .bind() locks in both this ({ name: "Amara" }) and the first argument ("Hi"). Calling hi() needs no arguments and always uses that this.
What is `this` inside an IIFE (immediately invoked function expression) written as a plain function, called with no object?
The same as any standalone call: undefined in strict mode, otherwise the global object. An IIFE is still a regular function call with nothing to its left.
If an arrow function is defined directly inside a regular method, does it correctly inherit that method's `this`?
Yes. This is a main reason arrow functions exist. With no this of their own, an arrow function inside a method picks up the method's this, which is usually what you want for a nested helper or callback.
Can you reassign `this` inside a function body the way you would a normal variable, like `this = someObject;`?
No. this isn't a variable; it's set by how the function was called. Assigning to it is a syntax error.
Does calling `.call()` or `.apply()` on an arrow function actually change what `this` resolves to inside it?
No. Arrow functions ignore any this passed via .call, .apply or .bind. Other arguments are still passed normally.
If you pass an object's method directly as the callback to `array.map(obj.method)`, what typically goes wrong with `this` inside it?
The same detached-method problem: map calls it as a plain function, not obj.method(), so this isn't obj. Fix it with an arrow wrapper (array.map(x => obj.method(x))), pre-binding (array.map(obj.method.bind(obj))), or by passing obj as map's optional second argument, thisArg.
Debugging: an event listener written as `element.addEventListener("click", instance.handleClick)` logs `this.state` as `undefined` instead of the expected instance data. What's the fix?
Passing instance.handleClick as a bare reference detaches it from instance. When the browser calls it, this is the element, not instance. Bind it, instance.handleClick.bind(instance), or define it as a class field arrow function, so this stays instance however the browser calls it.