The "this" keyword (concept)
Computer Science · JavaScript
Question 1 of 10
0The value of this in JavaScript is determined mainly by:
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
The "this" keyword (concept) explained
The value of this is decided by how a function is called, not where it is written. When a function is called as a method, this is usually the object the method was called on.
When a method is called as user.greet(), this is user. When a function is called on its own, this is undefined in strict mode, which modules and classes use automatically. The new keyword sets this to the newly created object. The call, apply and bind methods set this explicitly, and bind returns a new function permanently attached to the given object.
const user = { name: "Ada", greet() { return "Hi " + this.name; } };
const bound = user.greet.bind({ name: "Linus" });
console.log(user.greet());
console.log(bound());
Losing the context is a common bug. Copying a method into a variable, or passing it as a callback, detaches it from its object. Arrow functions have no this of their own; they use the this of the scope where they were written.
Worked example
user.greet() is called as a method, so this is user and the result is Hi Ada. bound is the same function with this fixed to the object containing Linus by bind, so bound() returns Hi Linus, however it is called.
What you will practise
105 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- In a method, this refers to:
- Arrow functions handle this by:
- At the top level, this is:
- call() and apply():
- A regular function’s this is:
- Which operator is used with a constructor function to create a new object?
- What does fn.bind(obj) return?
- Inside a regular (non-arrow) event listener function, this refers to:
…and 97 more.