【发布时间】:2018-12-31 14:58:09
【问题描述】:
当我尝试运行在这个 sn-p 中定义的 foo 函数时,我得到一个 ReferenceError,因为 b is not defined。
var b = 3;
function foo( a = 42, b = a + b + 5 ) {
// ..
}
foo()
这看起来像一个 TDZ 错误,因为 b 已在外部范围中定义,但它还不能在函数签名中用作右侧值。
这是我认为编译器应该做的:
var b;
function foo(..) { .. }
// hoist all functions and variables declarations to the top
// then perform assignments operations
b = 3;
foo();
//create a new execution environment for `foo`
// add `foo` on top of the callstack
// look for variable a, can't find one, hence automatically create a
`var a` in the local execution environment and assign to it the
value `42`
// look for a `var b` in the global execution context, find one, use
the value in it (`3`) as a right-hand-side value.
这不应该引发 ReferenceError。看起来这不是这里发生的事情。
有人能解释一下编译器到底做了什么以及它是如何处理这段代码的吗?
【问题讨论】:
标签: javascript function