执行上下文、可执行代码
V8引擎看待整个程序,将程序分成两部分:执行上下文(执行环境)和可执行代码。
class EnvironmentRecord(){
constructor(bindings){
this.bindings = bindings || {};
}
createBinding(){}
setBinding(){}
hasBinding(){}
getBindingValue(){}
}
class LexicalEnvironment(){
constructor(environmentRecord, outer){
this.environmentRecord = environmentRecord;
this.outer = outer;
}
//获取标识符方法。
getIdentify(){}
}
class ExecuteContext{
constructor( lexicalEnvironment, thisBinding ){
//词法环境
this.lexicalEnvironment = lexicalEnvironment;
//this指针
this.thisBinding = thisBinding;
}
}
class ExecuteContextStack{
constructor(){
this.executionContexts = []
}
push(){}
pop(){}
//获取当前的执行上下文。
get current(){}
}
class Function() {
constructor(name, code, scope){
this.name = name;
this.code = code;
this.scope = scope;
}
}
//创建全局环境记录项。
const globalEnvironmentRecords = new EnvironemntRecode(global);
//创建全局词法环境,外部词法环境为null
const globalLexicalEnvironment = new LexicalEnvironment(globalEnvironmentRecords, outer = null);
//创建全局执行上下文
const globalExecuteContext = new ExecuteContext(globalLexicalEnvironment, this = global);
//创建执行上下文栈
const ExecuteContextStack = new ExecuteContextStack();
ExecuteContextStack.push(globalExecuteContext);
//编译阶段,登记全局变量a
ExecuteContextStack.current.LexicalEnvironment.createBinding('a');
ExecuteContextStack.current.LexicalEnvironment.setBinding('a', undefined);
//登记函数,关键点在于当前函数所在的词法环境,作为函数的属性。(静态作用域)
let oneFn = new Function('one', 'var b = 2; console.log(b)', ExecuteContextStack.current.LexicalEnvironment)
ExecuteContextStack.current.LexicalEnvironment.createBinding('one');
ExecuteContextStack.current.LexicalEnvironment.setBinding('a', oneFn);
//执行赋值
ExecuteContextStack.current.LexicalEnvironment.setBinding('a', 1);
//函数执行,会创建一个新的词法环境
const functionLexicalEnvironment = new LexicalEnvironment(fnEnvironmentRecords, oneFn.scope);
作用域
词法环境
词法环境本质上是一个类,用来定义标识符的属性和方法以及嵌套关系的类型。
关键点函数声明、with语句、try…catch语句都会创建一个新的词法环境。
执行上下文
执行上下文 = 词法环境 + this
关键点词法环境是执行上下文的一个属性。
可执行代码
参考
https://www.bilibili.com/video/BV1cR4y1F7ba?p=2