Question 20 / 31
Does passing obj.foo into another function carry obj along with it?
Topic: this bindingDifficulty: Intermediate
A function argument is just a value — its original receiver is never part of that value.
Solve it with the execution visualizerStep through every binding, function call, and console output below.Predict the output
Predict both lines. doFoo receives obj.foo as fn and calls fn() — does fn still remember obj?
function foo() {
console.log(this.a);
}
function doFoo(fn) {
console.log(this);
fn();
}
var obj = { a: 1, foo };
var a = 2;
doFoo(obj.foo);Reveal the answer and explanation
Expected output
window
2Why this happens
doFoo(obj.foo) is called at the top level with no receiver, so inside doFoo, default binding applies: this is the global object, and console.log(this) logs it.
obj.foo is passed only as a value — a reference to the function object. The parameter fn holds that same function object, with no memory of obj.
Inside doFoo, fn() is called as a bare, receiver-less expression, so default binding applies again: this.a reads the global var a, which is 2.
What this question tests
- a this binding never travels along with a function value
- each call expression re-decides this from its own syntax
- default binding applies whenever a call has no receiver, however the function got there
Runtime assumptions
Assumes a classic sloppy-mode script, where the global object stands in for this in both receiver-less calls.