脚本的预编译

1、前言

预编译是JS语言的难点重点之一,难点在于不便理解,重点在于必须掌握。javascript

预编译实际上就是JS引擎的两次扫描,第一次扫描是检测声明,第二次扫描是执行代码。java

预编译分为脚本的预编译和函数调用的预编译,先来讲说脚本的预编译。git


2、脚本预编译

1. 过程

1.建立全局对象GO(GlobalObject)github

2.加载脚本文件函数

3.预编译:ui

  • 找出全部的变量声明,按照变量名加入全局对象,若是已经存在,忽略。
  • 找出全部的函数声明,按照函数名加入全局对象,若是已经存在同名变量或者函数,替换之。
  • 非声明不考虑。

4.解析执行代码spa

2. 解析

1.没有var的变量,都不是变量声明,所有认为是window的全局变量,不参与预编译。code

// console.log(aa); // Uncaught ReferenceError: aa is not defined
aa = 5;
console.log(aa); // 5
复制代码

2.即便在函数中,aa也是全局变量。(运行时)cdn

test();
function test() {
    aa = 5;
}
console.log(aa); // 5
复制代码

3.脚本中的全部声明变量,在脚本预编译阶段完成,全部变量的声明与实际书写位置无关。对象

console.log(aa); // undefined
var aa = 5;
console.log(aa); // 5
复制代码

4.脚本中的全部函数声明,在脚本预编译阶段完成,全部函数声明与实际书写位置无关。

console.log(hh); // f hh(){...}
function hh() {
    console.log('hh');
}
复制代码

5.脚本中,若是变量与函数同名,那么将覆盖变量。

console.log(haha); // f haha(){...}
var haha = 123;
function haha() {
    console.log(2333);
}
复制代码

6.脚本中,只有函数可以覆盖变量,可是变量没法覆盖函数。(注意: 函数优先级大于变量!)

console.log(haha); // f haha(){...}
function haha() {
    console.log(2333);
}
var haha = 123;
复制代码

7.脚本中,后面的函数声明会覆盖前面的函数声明,而且忽略参数。

haha(1); // 'haha2'
function haha(a) {
    console.log('haha1');
}
function haha(b,c) {
    console.log('haha2');
}
复制代码

3、本节思惟导图

源码地址: github.com/Knight174/M…
相关文章
相关标签/搜索