js预编译

2021-02-05  本文已影响0人  仔崽06

函数声明与函数表达式

定义函数的主要方法有三种

1.函数证明

function test(){
}

2.函数表达式

var test=function(){
}

3.new Function

var str=`return Hello${name}`
var test=new Function('name',str)
test('zdb')

函数预编译

函数预编译发生在函数执行的前一刻,分为4个步骤.

步骤
1.创建AO(Activation Object)对象,AO所谓执行期上下文.
2.找形参和变量声明,将变量和形参名作为AO对象的属性名,值为undefined.
3.将实参值和形参统一.
4.在函数体里面找函数声明,值赋予函数体.
function fn(a){
    console.log(a) //[Function: a]
    var a=123;
    console.log(a) //123
    function a(){}
    console.log(a) //123
    var b=function(){}
    console.log(b) //[Function: b]
    function d(){}
}
fn(1)

1.创建AO

// Activation Object
AO{}

2.将函数的形参和变量声明,作为AO对象的属性名,值为undefined

AO{
   a:undefined,
   b:undefined
}

3.将形参和实参统一.

AO{
   a:1,
   b:undefined
}

4.在函数体里查找函数,值赋予函数体

AO{
   a:[Function:a],
   b:undefined,
   d:[Function:d]
}

5.执行函数代码

AO{
   a:[Function:a],
   b:[Function: b],
   d:[Function:d]
}
function fn(a){
    console.log(a) //[Function: a]  AO读取a
    var a=123;  //AO a赋值为123 
    console.log(a) //123
    function a(){}  //预编译提升不再执行
    console.log(a) //123
    var b=function(){}  //将AO b赋值为[Function: b]
    console.log(b) //[Function: b]
    function d(){}  //预编译提升不再执行
    console.log(d)  // [Function: d]
}
fn(1)

全局预编译

步骤
1.创建GO(Global Object)对象.
2.寻找变量声明,并且当做属性放在GO对象里,值为undefined
3.寻找函数声明,值赋予函数体.
console.log(global) //[Function: global]
var global=100
function global(){
    
}
console.log(global) //100

1.全局创建GO对象.

GO{
}

2.寻找变量声明,并且当做属性放在GO对象里,值为undefined.

GO{
  global:undefined
}

3.寻找函数声明,值赋予函数体

GO:{
  global:[Function: global]
}

4.代码运行

console.log(global) //读取GO 这时候global成为[Function: global]
var global=100  //GO里的global已被改完100
function global(){
    
} //变量提升不执行
console.log(global) //100 GO里的global
function test(){
   console.log(b); //undefined
   if(a){
       var b=100
   }
   c=234
   console.log(c) //234
}
var a;
test()
a=10;
console.log(c) //234

1.创建全局GO

GO{
    a:undefined,
    test:[Function:test]
}

2.函数test执行前,预编译,创建AO

AO{
}

3.函数体寻找形参,声明变量,作为AO属性赋值undefined

AO{
  b:undefined
}

4.将函数形参,实参值统一.
5.在函数体内查找函数声明,值赋予函数体.
6.执行函数代码,if里的a默认为全局GO的a属性,a值为undefined所以if代码不执行.
7.函数体c未经var声明,默认c为GO属性并赋值234

GO{
 a:undefined
 c:123
}

8.console.log(c),值为GO里的c打印234
9.test函数执行完毕,执行a=10,全局GO属性a修改值为10
10.console.log(c) 读取是GO的c,所以值为234

function test(){
   var a=b=123 
}
console.log(window.a) //undefined
console.log(window.b) //123

1.变量赋值至右向左.
2.函数体内没有var声明的变量默认为全局变量.

imply global 暗示全局变量

如果未经声明的变量赋值,比变量默认为全局变量所有

console.log(a) //error

//imply global 
 a=100
 console.log(a)  //100
 console.log(window.a) //100
上一篇 下一篇

猜你喜欢

热点阅读