Intermediate JavaScript Interview QuestionsIntermediateCode Output
JavaScript · Question 38
What happens to this when a method is detached from its object?
Direct answer
Detaching a regular method removes the object-method call site; when the detached function is called plainly, it no longer receives the original object as this.
detached-method-this.js
"use strict";
const user = { name: "Ada", getName() { return this.name; } };
const getName = user.getName;
console.log(user.getName());
getName();Output
Ada TypeError: Cannot read properties of undefined (reading 'name')
Given const user={name:'Ada', getName(){ return this.name; }}; const getName=user.getName;, the expressions user.getName() and getName() have different call sites.
user.getName() uses user as the receiver and returns 'Ada'. In strict-mode code, a plain getName() call gives the function undefined as this, so trying to read this.name throws. Behavior involving a global object in non-strict classic scripts should not be relied on.
- Preserve the receiver with
const getName = user.getName.bind(user);. - Or wrap the invocation:
const getName = () => user.getName();. - This issue commonly appears when methods are passed as callbacks without binding.