Understanding this, call, apply and bind
Master the rules for what this means in JavaScript and control it with call, apply, bind and arrow functions.
In this lesson you will
- State the rules for this
- Spot and fix a lost this
- Use arrow functions for callbacks
- Control this with call, apply and bind
About 19 minutes
The word that changes its meaning
The word “I” means a different person depending on who is speaking. In JavaScript, this works the same way. It is a word that points to something, and what it points to depends on how a function is called, not where it was written. This single fact explains a whole family of confusing bugs, and once you see the rules, this stops being scary.
Rule 1: method call, this is the object before the dot
const user = {
who: "Sara",
hello() {
console.log("Hi, I am " + this.who);
}
};
user.hello(); // this = user -> "Hi, I am Sara"
const other = { who: "Ali", hello: user.hello };
other.hello(); // this = other -> "Hi, I am Ali"
Rule 2: plain function call, this is undefined or global
function show() {
console.log(this);
}
show(); // sloppy mode: the global object; strict mode/modules: undefined
const fn = user.hello;
fn(); // the dot is gone, so this is lost: "Hi, I am undefined"
This is the most common bug. Passing a method as a callback, such as setTimeout(user.hello, 1000) or button.addEventListener("click", user.hello), detaches it from the object, and this no longer points to user.
Run this and read the output. The second call loses this. Why does it print undefined?
const user = {
who: 'Sara',
hello() { console.log('Hi, I am ' + this.who); }
};
user.hello();
const detached = user.hello;
detached();
detached() has no object before the dot, so this is not user.
const user = {
who: 'Sara',
hello() { console.log('Hi, I am ' + this.who); }
};
user.hello();
const detached = user.hello;
try { detached(); } catch (e) { console.log('Error: ' + e.message); }
Rule 3: arrow functions have no this of their own
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // arrow: this comes from start(), so it is timer
console.log(this.seconds);
}, 1000);
}
};
const broken = {
seconds: 0,
start() {
setInterval(function () {
this.seconds++; // regular function: this is NOT broken
}, 1000);
}
};
An arrow function does not create its own this. It uses the this of the place where it was written. That makes arrows perfect for callbacks inside methods, and a poor choice for the methods themselves.
| Where | Use |
|---|---|
| Object methods | Regular method syntax: hello() { ... } |
| Callbacks inside methods | Arrow functions |
| Event handlers that need the element | Regular function (this = the element), or use e.currentTarget |
Rule 4: you choose this with call, apply and bind
function intro(greeting, punctuation) {
return greeting + ", I am " + this.name + punctuation;
}
const sara = { name: "Sara" };
const ali = { name: "Ali" };
console.log(intro.call(sara, "Hello", "!")); // call: arguments one by one
console.log(intro.apply(ali, ["Salaam", "."])); // apply: arguments in an array
const saraIntro = intro.bind(sara); // bind: returns a NEW function
console.log(saraIntro("Hey", "?"));
call(thisValue, a, b)runs the function now with a chosenthis.apply(thisValue, [a, b])is the same, with arguments in an array.bind(thisValue)does not run it; it returns a new function withthispermanently fixed.
Fix the detached method using bind so the setTimeout callback prints the user’s name.
const user = {
who: 'Sara',
hello() { console.log('Hi, I am ' + this.who); }
};
setTimeout(user.hello, 100);
setTimeout(user.hello.bind(user), 100); or wrap it in an arrow function.
const user = {
who: 'Sara',
hello() { console.log('Hi, I am ' + this.who); }
};
setTimeout(user.hello.bind(user), 100);
Rule 5: new creates a fresh object
function Person(name) {
this.name = name; // this = the brand-new object
}
const p = new Person("Sara");
console.log(p.name); // Sara
When you call a function with new, JavaScript creates an empty object, points this to it, runs the function, and returns the object. This is the foundation of classes, the topic of the next lesson.
A quick checklist when this goes wrong
- Find the call. How was the function called?
- Is there something before the dot? That is
this. - Was it passed as a callback? Then it was detached. Use an arrow wrapper or
bind. - Is it an arrow function? Then
thiscomes from outside it. - Add
console.log(this)at the top of the function and look.
this in the browser
button.addEventListener("click", function () {
console.log(this === button); // true: this is the element
this.classList.add("clicked");
});
button.addEventListener("click", (e) => {
console.log(this === button); // false: arrow, this is from outside
e.currentTarget.classList.add("clicked"); // reliable alternative
});
Using an arrow function as an object method: hello: () => console.log(this.name). Its this comes from the code around the object (often the global object), not from the object itself, so this.name is undefined. Use the short method form instead.
Many modern codebases avoid this where they can, passing data as parameters or using closures instead. Both are fine. Knowing the rules helps you read other people’s code and fix bugs quickly.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
In user.hello(), what is this?
- window
- user
- hello
- undefined
The object before the dot.
Why does const f = user.hello; f(); lose this?
- f is a constant
- hello is private
- The method was detached from its object
- Arrow functions are broken
There is nothing before the dot.
Which function does NOT have its own this?
- Arrow function
- Regular function
- Method
- Constructor
Arrows use the surrounding this.
What does bind return?
- The result of calling it
- An array
- A new function with this fixed
- undefined
bind does not call; it returns a bound function.
What does call do differently from apply?
- Passes arguments individually instead of in an array
- Nothing
- Delays the call
- Binds permanently
call takes arguments one by one.
Summary
- this depends on how a function is called.
- Detached methods lose this.
- Arrow functions borrow this from outside.
- call, apply and bind set this explicitly.
Questions
Why is this undefined in strict mode?
In strict mode a plain function call gets no automatic object, so this is undefined, which exposes mistakes.
Should I use bind or an arrow function?
Either. An arrow wrapper such as () => user.hello() is usually the most readable.
What does globalThis refer to?
It is the global object in any environment: window in browsers, global in Node.
