LearnFrenzy
Sign in Take a free test

Objects · Find the Error · Question 7

Error: a detached method in strict mode Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The code below stops with an uncaught error. Which statement correctly describes the problem?

main.js
"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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links