Question 7
Back to Exercise
The code below stops with an uncaught error. Which statement correctly describes the problem?
"use strict";
const counter = {
count: 0,
inc() { this.count++; },
};
const onClick = counter.inc; // e.g. passed to an event handler
onClick();
console.log(counter.count);
- A It prints 1
- B It prints 0
- C It prints NaN
- D TypeError: onClick() is called without an object, so this is undefined in strict mode – use counter.inc.bind(counter) Correct
Correct Answer: Option D
this is decided by the call, not by where the method was defined. A plain call gives undefined in strict code (the global object in sloppy code), and undefined.count throws. bind(counter) or () => counter.inc() keeps the object.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!