js预编译

本文主要介绍了JavaScript的预编译过程,包括全局变量的声明、函数声明的处理,以及预编译与执行的区别。总结了预编译的三步:创建全局对象(Global Object,即window)、处理变量声明和函数声明。在预编译阶段,未声明变量赋值会成为全局window属性,函数声明会被赋予函数体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结:

1.未经声明就赋值的变量归全局window所有

function test() {
  var a=b=123
}

console.log(b) // 123 未经声明就赋值的变量属于全局

全局声明的变量也为window一个属性

2.三步曲,对比函数预编译仅仅缺少形参实参统一:

    (1)生成一个GO对象 (Global Object)  GO ===window

    (2)找变量声明,将变量声明名作为GO属性名,值为undefined

    (3)找函数声明,值赋予函数体,注意不是函数表达式

global = 100;
function fn(){
	console.log(global);
	global = 200;
	console.log(global);
	var global = 300;
}
fn();
var global;

结果为

a=100;
console.log(demo)
function demo(e){
	function e(){}
	arguments[0] =2;
	console.log(e);
	if(a){
		var b = 123;
		function c(){
			//...
		}
	}
	var c;
	a=10;
	var a;
	console.log(b);
	f=123;
	console.log(c);
	console.log(a);
}
var a;
demo(1);
console.log(a);
console.log(f);

预编译 

1.首先生成GO
2.找变量声明 var a 赋值 undefined
   GO{
        a:undefined
   }
3.找函数声明 function demo(){...} 赋值函数体
   GO{
        a:undefined
        demo:function demo(){...}
   }

执行

1.a=100 改变GO中a的值
  GO{
        a:100
        demo:function demo(){...}
   }
2.console.log(demo) 打印function demo(e){...}
3.跳过函数声明,跳过 var a
4.demo(1) 执行函数前先函数预编译

  函数预编译
  1.生成AO{}
  2.形参和变量声明赋值为undefined
   AO{
     e:undefined
     b:undefined
     c:undefined
     a:undefined
   }
  3.形参实参统一
   AO{
     e:1
     b:undefined
     c:undefined
     a:undefined
   }
  4.函数声明
   AO{
     e:function e(){}
     b:undefined
     c:undefined
     a:undefined
   }
   新标准if(){}中不可以定义函数,所以此处c未改变

   编译完成执行函数
   4-1.跳过function e(){}
   4-2.arguments[0] =2;  arguments[0]与形参e映射,虽为两个个体,值改变时另一个改变
   AO{
     e:2
     b:undefined
     c:undefined
     a:undefined
   }
   4-3.console.log(e) 结果为2
   4-4.if(a)条件不成立 不执行
   4-5.跳过var c;
   4-6.a=10;a赋值为10
   AO{
     e:2
     b:undefined
     c:undefined
     a:10
   }
   4-7.console.log(b) 结果为undefined
   4-8.f=123;未声明的变量为window的属性,GO中f赋值为123
      GO{
        a:100
        demo:function demo(){...}
        f:123
      }
   4-9.console.log(c) 结果为undefined
   4-10.console.log(a) 结果为10

5.console.log(a) 结果为100
6.console.log(f) 结果为123

结果为

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值