Question 21 / 31
Why does the destructured getName still know the instance?
Topic: this bindingDifficulty: Advanced
An arrow function created inside a constructor permanently captures that constructor call's this.
Solve it with the execution visualizerStep through every binding, function call, and console output below.Predict the output
Predict both lines. The second call destructures getName away from cat before calling it — does it still work?
function Pet(name) {
this.name = name;
this.getName = () => this.name;
}
const cat = new Pet('Fluffy');
console.log(cat.getName());
const { getName } = cat;
console.log(getName());Reveal the answer and explanation
Expected output
Fluffy
FluffyWhy this happens
new Pet('Fluffy') triggers the Construct operation: a fresh object is allocated and bound as this for the Pet call, and this.name is set to 'Fluffy' on it.
this.getName = () => this.name creates an arrow function while Pet is executing. That arrow has no this of its own — it lexically captures the this of the enclosing Pet call, which is the newly constructed instance, permanently.
cat.getName() logs 'Fluffy'. Destructuring const { getName } = cat only copies out the function value; the arrow's captured this does not depend on how or where it is later called, so getName() alone also logs 'Fluffy'.
What this question tests
- new binds this to the newly created instance for the whole constructor call
- an arrow function defined inside a constructor locks in that instance as this forever
- unlike an ordinary method, a detached arrow function does not lose its this
Runtime assumptions
This behavior is specific to arrow functions; if getName were an ordinary method instead, destructuring it away would lose the instance and its this would fall back to default binding.