《You Don’t Know JS》中变量b未被作用域找到引发ReferenceError的疑问
b isn't found in the scope? Great question! Let's unpack this using the scope rules explained in Kyle Simpson's You Don’t Know JS: Scope & Closures.
First, let's recap how JavaScript looks up variables: when your code tries to access a variable (like reading its value, which is what happens in a + b), it performs an RHS reference lookup. Here's the step-by-step breakdown for your code:
- When
foo(2)runs, we enter the local scope of thefoofunction. - The engine first looks for
ain this local scope—sinceais a function parameter, it's already declared here, so that works fine. - Next, it tries to find
bto get its value for thea + bcalculation. It checks the local scope offoofirst... and there's novar b,let b, orconst bdeclared here. - Then it moves up to the outer (global) scope to look for
b—but there's no declaration forbin the global scope either.
Since the engine can't find b anywhere in the scope chain during this RHS lookup, it throws a ReferenceError immediately. The line b = a never even gets a chance to run, because the error happens before that.
It's important to note: if this were an LHS reference (like if you were assigning to b first without reading it), JavaScript would create a global b variable in non-strict mode. But in your case, we're trying to read b first, which triggers the failed RHS lookup and the error.
The key takeaway from You Don’t Know JS here is that scope lookup stops at the first match, and if no match is found in the entire chain, RHS lookups throw ReferenceErrors, while LHS lookups in non-strict mode create a global variable.
内容的提问来源于stack exchange,提问作者Maruf Hasan

