Calls and With Statements
JavaScript Corners – Part 7
Calls and With Statements
Here’s a quick one. What does the following print? (Assuming not in strict mode)
function foo() { console.log(this.name); } const bar = { foo, name: 'Bar' }; global.name = 'Global'; foo(); // Case 1 bar.foo(); // Case 2 with (bar) { foo(); // Case 3 }
In non-strict mode, the naked function call foo() gets a this value that is the global object. So the first case prints “Global”.
In the second case, we’re invoking foo
as a member of bar, and so the this value is bar
(it prints “Bar”).
The last case is the most interesting, and the most useless (since with
statements are strongly discouraged, and cannot be used outside of non-strict mode). The this object in this case is actually bar. JavaScript recognizes that the function foo
here is being invoked within the context of a with statement, and implicitly uses the bar object. This prints “Bar”.
One Reply to “JavaScript Corners – Part 7
Calls and With Statements”