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
Show answer & explanation
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:
person1.getDetails.call(person2)invokesgetDetailswiththisbound toperson2.this.name→ 'Jane Doe'this.age→ 25- Output: "Jane Doe is 25 years old."
person1.getDetails.apply(person2)also invokesgetDetailswiththisbound toperson2(no additional arguments passed).this.name→ 'Jane Doe'this.age→ 25- Output: "Jane Doe is 25 years old."
Final output: Both lines print the same string.