OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

36.

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

(JavaScript) this

What will be the output?

const object = {
  abc: function () {
    return this;
  },

  def: function () {
    return function () {
      return this;
    }
  }
};

console.log(object.abc());
console.log(object.def()());

Pick ONE option

Choose one option.
Show answer & explanation
Answer: A. "Object" object "Window" object

In JavaScript, the value of this depends on how a function is called. When object.abc() is invoked as a method on object, this refers to object itself (the "Object"). However, object.def()() returns a regular function that is called without an object context, so this defaults to the global window object in non-strict mode.

Step-by-step Derivation:
Step 1: object.abc() - The function abc is called as a method on object. Method call binding means this === object, so it returns the object.

Step 2: object.def()() - The function def is called as a method (returns object), but it returns an anonymous function. When that anonymous function is immediately invoked with (), it's called in global scope without method context. In non-strict mode, this defaults to the global window object.

Output: First console.log prints the object (displays as "[object Object]" or similar), second console.log prints the window object.