当您创建函数时,它们会在运行时编译。在调用函数时,将调用该函数。
让我解释一下:
您可以拥有任意数量的函数上下文,并且每个函数调用都会创建一个新的上下文。
var helloWorld = "hello world!";
function foo(){
function bar(){
console.log('bar');
}
}
foo();
所以,在上述代码中,函数 foo 被调用,为函数 foo 创建了新的上下文环境并且调用 bar 的执行上下文仅在您调用它时创建,但在运行时已经被编译。
当脚本首次被浏览器加载时,默认进入全局执行上下文。如果在全局范围内调用函数,则程序的流程顺序进入被调用的函数,创建一个新的执行上下文并将其推到执行堆栈的顶部。
现在让我们详细了解一下执行上下文:
所以,每次调用函数都会创建一个新的执行上下文。每个执行上下文的调用有两个阶段:
1.创建阶段:
当函数被调用但在执行任何代码之前:创建作用域链、创建变量、函数和参数,并确定“this”的值。
2.激活阶段:
分配值、引用函数并执行代码。
现在,让我们更加了解执行上下文。请参阅
此链接。
function foo (a, b, c) {
function z(){alert(‘Z!’);}
var d = 3;
}
foo(‘foo’,’bar’);
在foo()调用中的ExecutionContext: 第一步:创建arguments
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function()
}
}
步骤3a:变量实例化,参数
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function()
},
a: ‘foo’, b: ‘bar’, c: undefined
}
第三步b:变量实例化,函数
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function()
},
a: ‘foo’, b: ‘bar’, c: undefined,
z: function()
}
步骤3c:变量实例化,变量
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function()
},
a: ‘foo’, b: ‘bar’, c: undefined,
z: function(),
d: undefined
}
步骤4:设置此值。
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function()
},
a: ‘foo’, b: ‘bar’, c: undefined,
z: function(),
d: undefined,
this: window
}
创建了ExecutionContext之后,函数从第一行开始执行其代码,直到找到一个return语句或函数结束。每次该代码尝试访问变量时,都会从ExecutionContext对象中读取它。