执行上下文在 JavaScript
Execution context's in JavaScript
我正在尝试掌握执行上下文并对循环有疑问。
考虑以下...
function copyArrayAndMutate(array, instructions) {
let output = []
for(let i = 0; i < array.length; i++) {
output.push(instructions(array[i]));
}
return output;
}
function multiplyByTwo(input) {
return input * 2;
}
const result = copyArrayAndMutate([1,2,3], multiplyByTwo)
在高层次上,我了解到这些函数将在全局执行上下文中定义,一旦被调用,它们将创建自己的本地执行上下文并且执行线程将移至该上下文中,其中包含用于上下文被推入堆栈。
我的问题是,for 循环是否有自己的执行上下文?如果是这样,并且执行上下文有自己的内存,那么输出如何仍然存在于 for 循环的上下文中?
这是因为for循环的本地执行上下文存在于copyArrayAndMutate的上下文中吗?
My question is, will the for loop have it's own execution context?
没有。
My question is, will the for loop have it's own execution context?
NO. foor 循环不会它自己的执行上下文。 只有函数会创建新的执行上下文。
每次调用函数时,都会创建一个新的执行上下文,即使函数调用在另一个函数定义中也是如此。该函数可用的范围由其词法环境定义:
总之,for循环的执行上下文是copyArrayAndMutate
函数创建的,即for循环使用的范围是属于copyArrayAndMutate
执行上下文的,这就是循环可以访问 output
变量的原因。
我正在尝试掌握执行上下文并对循环有疑问。
考虑以下...
function copyArrayAndMutate(array, instructions) {
let output = []
for(let i = 0; i < array.length; i++) {
output.push(instructions(array[i]));
}
return output;
}
function multiplyByTwo(input) {
return input * 2;
}
const result = copyArrayAndMutate([1,2,3], multiplyByTwo)
在高层次上,我了解到这些函数将在全局执行上下文中定义,一旦被调用,它们将创建自己的本地执行上下文并且执行线程将移至该上下文中,其中包含用于上下文被推入堆栈。
我的问题是,for 循环是否有自己的执行上下文?如果是这样,并且执行上下文有自己的内存,那么输出如何仍然存在于 for 循环的上下文中?
这是因为for循环的本地执行上下文存在于copyArrayAndMutate的上下文中吗?
My question is, will the for loop have it's own execution context?
没有。
My question is, will the for loop have it's own execution context?
NO. foor 循环不会它自己的执行上下文。 只有函数会创建新的执行上下文。
每次调用函数时,都会创建一个新的执行上下文,即使函数调用在另一个函数定义中也是如此。该函数可用的范围由其词法环境定义:
总之,for循环的执行上下文是copyArrayAndMutate
函数创建的,即for循环使用的范围是属于copyArrayAndMutate
执行上下文的,这就是循环可以访问 output
变量的原因。