Challenge - 5 Problems
Master of this keyword
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of this in a regular function
What is the output of the following code when calling
obj.show()?Javascript
const obj = { name: 'Alice', show: function() { console.log(this.name); } }; obj.show();
Attempts:
2 left
💡 Hint
Inside an object method,
this refers to the object itself.✗ Incorrect
When a function is called as a method of an object, this refers to that object. So this.name is obj.name, which is "Alice".
❓ Predict Output
intermediate2:00remaining
Value of this in arrow function inside object
What will be logged when calling
obj.show() in this code?Javascript
const obj = { name: 'Bob', show: () => { console.log(this.name); } }; obj.show();
Attempts:
2 left
💡 Hint
Arrow functions do not have their own
this.✗ Incorrect
Arrow functions inherit this from their surrounding scope. Here, this is not obj, so this.name is undefined.
❓ Predict Output
advanced2:00remaining
this inside event listener function
What does
this refer to inside the event listener function in this code?Javascript
const button = document.createElement('button'); button.textContent = 'Click me'; document.body.appendChild(button); button.addEventListener('click', function() { console.log(this); });
Attempts:
2 left
💡 Hint
In event listeners,
this refers to the element the listener is attached to.✗ Incorrect
In a regular function used as an event listener, this points to the element that received the event, here the button.
❓ Predict Output
advanced2:00remaining
this in class method with setTimeout
What will be logged when calling
obj.delayedShow()?Javascript
class Person { constructor(name) { this.name = name; } delayedShow() { setTimeout(function() { console.log(this.name); }, 100); } } const obj = new Person('Carol'); obj.delayedShow();
Attempts:
2 left
💡 Hint
Regular functions inside
setTimeout have this as the global object or undefined in strict mode.✗ Incorrect
The function inside setTimeout is a regular function, so this is not the class instance. It is undefined in strict mode, so this.name is undefined.
🧠 Conceptual
expert2:00remaining
Understanding this binding with call, apply, and bind
Given the code below, which option correctly shows the output of
greet.call(person, 'Hello')?Javascript
function greet(greeting) { return `${greeting}, my name is ${this.name}`; } const person = { name: 'Dave' };
Attempts:
2 left
💡 Hint
call sets this explicitly to the first argument.✗ Incorrect
The call method calls the function with this set to person. So this.name is "Dave".