预编译

通篇检查语法错误

全局预编译

全局产生GO,global object,全局上下文

现象

  1. foo(); // 这里正常运行
  2. function foo(){}
  3. console.log(a); // 这里也正常运行 undefined
  4. var a; // 或者 var a = 10;

声明提升

函数声明整体提升,变量只有声明提升,赋值不提升

  1. var a = 1;
  2. function a(){
  3. }
  4. console.log(a);
  5. // 1. 找变量
  6. GO = {
  7. a: undefined
  8. }
  9. // 2. 找函数声明
  10. GO = {
  11. a: function a(){}
  12. }
  13. // 3. 执行

函数预编译

函数将要执行时会生成一个AO,active objcet,函数上下文。

  1. function foo(a){
  2. console.log(a);
  3. var a = 1;
  4. console.log(a);
  5. function a(){}
  6. console.log(a);
  7. var b = function(){};
  8. console.log(b);
  9. function d(){}
  10. }
  11. // 1. 找到所有的变量声明(形参也是变量声明)
  12. AO = {
  13. a: undefined,
  14. b: undefined
  15. }
  16. // 2.绑定实参与形参绑定
  17. AO = {
  18. a: 2,
  19. b: undefined
  20. }
  21. // 3.找到函数声明覆盖
  22. AO = {
  23. a: function a(){},
  24. b: undefined
  25. }
  26. // 4. 执行函数

解释一行,执行一行

  1. var b = 3;
  2. console.log(a);
  3. function a(a){
  4. console.log(a);
  5. var a = 2;
  6. console.log(a);
  7. function a(){}
  8. var b = 5;
  9. console.log(b);
  10. }
  11. a(1);
  1. a = 1;
  2. function test(){
  3. console.log(a);
  4. a = 2;
  5. console.log(a);
  6. var a = 3;
  7. console.log(a);
  8. }
  9. test();
  10. var a;
  1. function test(){
  2. console.log(b);
  3. if (a){
  4. var b = 2;
  5. }
  6. console.log(b);
  7. c = 3;
  8. console.log(c);
  9. }
  10. var a;
  11. test();
  12. a = 1;
  13. console.log(a);
  1. function test(){
  2. return a;
  3. a = 1;
  4. function a(){}
  5. var a = 2;
  6. }
  7. test();
  1. a = 1;
  2. function test(e){
  3. function e(){}
  4. arguments[0] = 2;
  5. console.log(e);
  6. if (a){
  7. var b = 3;
  8. }
  9. var c;
  10. a = 4;
  11. var a;
  12. console.log(b);
  13. f = 5;
  14. console.log(c);
  15. console.log(a);
  16. }
  17. var a;
  18. test(1);
  19. console.log(a);
  20. console.log(f);

暗示全局变量

imply global variable

  1. // 全局下
  2. a = 1; // 这样的操作等于是window.a = 1;
  3. // 全局下声明的变量自动挂载到window下
  4. var a = 1;
  1. // 函数下
  2. function foo(){
  3. var a = b = 1; // b将会被挂载到window下
  4. }