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

30.

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

30. Function Borrowing

What is the output of the following code?

const person1 = {
  name: 'John Doe',
  age: 30,
  getDetails() {
    return `${this.name} is ${this.age} years old.`;
  }
};

const person2 = {
  name: 'Jane Doe',
  age: 25
};

console.log(person1.getDetails.call(person2));
console.log(person1.getDetails.apply(person2))

Pick ONE option

Choose one option.
Show answer & explanation
Answer: B. Jane Doe is 25 years old. Jane Doe is 25 years old.

Both .call() and .apply() explicitly bind the function's this context to person2. When person1.getDetails is called with either method on person2, the function executes in the context of person2, so this.name becomes 'Jane Doe' and this.age becomes 25. Both console.log statements output the same result because both methods perform function borrowing with the same context.

Step-by-step Derivation:

  1. person1.getDetails.call(person2) invokes getDetails with this bound to person2.

    • this.name → 'Jane Doe'
    • this.age → 25
    • Output: "Jane Doe is 25 years old."
  2. person1.getDetails.apply(person2) also invokes getDetails with this bound to person2 (no additional arguments passed).

    • this.name → 'Jane Doe'
    • this.age → 25
    • Output: "Jane Doe is 25 years old."
  3. Final output: Both lines print the same string.