functiontest() { // 这里就是 a =1 console.log(a); // 然后再赋值 var a = 1; }
test();
这里的变量a进行了提升,先定义(!把定义提升!)后(!在其赋值位置!)赋值,如果不存在 var 就不会提升,接着就是未定义报错。而函数表达式(function t(){} )会提升最高,如果用 var t = function (){} 的形式则根据变量原则提升。而在 ES6 中使用 let 和 const 不存在提升。
1 2 3 4 5 6 7 8 9 10 11
functiontest() { console.log(1); }
test();
var test = function() { console.log(2); };
test();
这里就会输出 1 和 2。
1 2 3 4 5 6 7 8
var a =20; functiont1(){ console.log(a) } (functiont2() { var a = 10; t1() })()
1 2 3 4 5 6 7 8 9
var scope = "global scope"; functioncheckscope(){ var scope = "local scope"; functionf(){ return scope; } returnf(); } checkscope();
1 2 3 4 5 6 7 8 9
var scope = "global scope"; functioncheckscope(){ var scope = "local scope"; functionf(){ return scope; } return f; } checkscope()();