LearnFrenzy
Sign in Take a free test

Arrow Functions · Predict the Output · Question 20

A library that calls handlers with call() Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
const emitter = {
  name: "emitter",
  fire(handler) { return handler.call(this); },
};
const widget = {
  name: "widget",
  init() {
    return [emitter.fire(function () { return this.name; }), emitter.fire(() => this.name)];
  },
};
console.log(widget.init());
  • A [ 'widget', 'widget' ]
  • B [ 'emitter', 'emitter' ]
  • C [ 'widget', 'emitter' ]
  • D [ 'emitter', 'widget' ] Correct
Correct Answer: Option D

The emitter calls handlers with this = emitter (as DOM event listeners do with the element). A regular handler receives it; the arrow ignores call's this and keeps init()'s this, the widget.

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