在foo这里创建函数时,我引用了fromTheFuture尚未声明的变量.这实际上按预期工作,但为什么?它被认为是危险的还是不好的做法?
var foo = function(x) {
return fromTheFuture * x;
};
var fromTheFuture = 5;
console.log(foo(10));
Run Code Online (Sandbox Code Playgroud)
我可以看到这非常方便,如果你有几个函数想要以循环方式相互使用 - 而不必var在方法的开头声明它们.
到时候foo被称为,fromTheFuture被定义.更准确地说,由于提升,您的代码基本上是:
var foo, fromTheFuture;
foo = function(x) {return fromTheFuture*x;};
fromTheFuture = 5;
console.log(foo(10));
Run Code Online (Sandbox Code Playgroud)
如果你打电话foo(10)之前fromTheFuture=5,你会得到NaN.