Concept
The this keyword
The object a function is called on, decided at call time (except in arrow functions).
The this keyword explained
In JavaScript, this is decided by how a function is called, not where it is written. Called as a method (obj.fn()), this is obj; called with new, it is the new object; called with call, apply or bind, it is whatever you pass; called as a plain function, it is undefined in strict mode. Arrow functions are the exception: they have no this of their own and use the one from the surrounding code.
The rules, in order of priority
new:thisis the newly created object.- Explicit:
fn.call(obj),fn.apply(obj)or a function fromfn.bind(obj). - Method call:
obj.fn()setsthistoobj. - Plain call:
fn()givesundefinedin strict mode and modules (the global object in sloppy scripts). - Arrow functions skip all of the above and take
thisfrom where they were defined.
const user = {
name: "Asha",
hello() { return `Hi, ${this.name}`; },
};
user.hello(); // "Hi, Asha"
const fn = user.hello;
fn(); // TypeError in strict mode: this is undefined
class Timer {
seconds = 0;
start() {
setInterval(() => { this.seconds += 1; }, 1000); // arrow keeps the instance
}
}
Common mistakes
- Losing
thiswhen passing a method as a callback (button.onclick = obj.handle). Use an arrow wrapper orbind. - Using an arrow function as an object method and expecting
thisto be the object. - Forgetting
newwith a constructor function, sothisis not a fresh object.
What interviewers ask about this
- "What will
thisbe here?" Find the call site and apply the rules above. - "
call,applyorbind?"callandapplyinvoke now (arguments listed or as an array);bindreturns a new function for later. - "Why do arrow functions help in callbacks?" They keep the outer
this.
Learn firstObjects
The this keywordCompared withArrow functions
What should you learn before The this keyword?
- ObjectsCollections of key–value properties, the building block of most JavaScript data.
Connections to other concepts
- Compared with
- Arrow functions
Practise The this keyword
- Intermediate JavaScript Interview Questions2 questions on The this keyword
- Top 20 JavaScript interview questions with answers: core JS, Node.js and React1 question on The this keyword