JavaScript中的“执行上下文”究竟是什么? [英] What is the 'Execution Context' in JavaScript exactly?

查看:147
本文介绍了JavaScript中的“执行上下文”究竟是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的头衔几乎总结了所有。

My title pretty much sums it all.

任何人都可以开导我......

Can anyone enlighten me on...

JavaScript中的'执行上下文'是什么?

以及它与'this',吊装,原型链,范围和垃圾收集?

and on how it relates to 'this,' hoisting, prototype chaining, scope and garbage collection?

推荐答案

你问的是几个不太密切相关的不同概念。我将尝试简要介绍每一个。

You're asking about several different concepts that aren't very closely related. I'll try to briefly address each.

执行上下文是一种语言概念用外行人的术语表达—大致相当于一个函数执行的'环境';也就是说,变量作用域(和作用域链,来自外部作用域的闭包中的变量),函数参数以及对象的值。

Execution context is a concept in the language spec that—in layman's terms—roughly equates to the 'environment' a function executes in; that is, variable scope (and the scope chain, variables in closures from outer scopes), function arguments, and the value of the this object.

调用堆栈是执行上下文的集合。

The call stack is a collection of execution contexts.

参见< a href =https://stackoverflow.com/a/7722057/201952>这个答案和这篇文章

范围字面意思是:可以访问变量的范围。简单地说:

Scope is literally that: the scope in which a variable can be accessed. Simplistically:

var x;

function a() {
    var y;
}

x 可以是从任何地方访问。当调用时, x 将在外部范围内。 (存储在范围链中。)

x can be accessed from anywhere. When a is invoked, x will be in the outer scope. (Stored in the scope chain.)

相比之下, y 只能是由 a()中的代码访问,因为它仅限于 a 的范围。这就是 var 关键字的作用:将变量限制为本地范围。如果我们省略 var ,那么 y 将最终出现在全局范围中,通常被认为是坏事。

In contrast, y can only be accessed by code in a() because it is limited to a's scope. This is what the var keyword does: restricts a variable to the local scope. If we omitted var, y would end up in the global scope, generally considered a bad thing.

提升想象成更多的编译时间。在JavaScript中,函数声明被提升到其范围的顶部。换句话说,它们在之前解析和评估任何其他代码。 (这与函数表达式相反,它们是内联计算的。)请考虑以下内容:

Think of hoisting as more of a compile-time thing. In JavaScript, function declarations are "hoisted" to the top of their scope. In other words, they are parsed and evaluated before any other code. (This is opposed to function expressions, which are evaluated inline.) Consider the following:

a();
b();

function a() { }
var b = function() { }

a()的调用将成功,因为它的声明已被提升到顶部;在程序执行开始之前, a 被自动分配。对 b()的调用将因 TypeError 而失败,因为 b 直到第4行才会定义。

The call to a() will succeed because its declaration was hoisted to the top; a was assigned to automatically before program execution began. The call to b() will fail with a TypeError because b will not be defined until line 4.

这篇关于JavaScript中的“执行上下文”究竟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆