执行上下文和Javascript中的执行上下文对象

Execution context and the execution context object in Javascript

本文关键字:执行 上下文 对象 Javascript      更新时间:2023-09-26

我的脑袋在转,有人能解释一下javascript是如何存储变量的,什么是"执行上下文"answers"执行上下文对象"吗?

为什么代码片段在控制台上打印以下输出:

你好论点

你好论点

var hello = 'hello is assigned';
function prison(hello) {
  console.log(hello);
  var hello;
  console.log(hello);
}
prison('the hello argument');

谢谢!

这与执行上下文没有太大关系,而与函数变量范围有关。将'the hello argument'作为参数传递给函数,并且作为本地参数,它将被使用,而不是在函数外部声明的hello var。

var hello什么都不做,如果使用use strict或linter,可能会引发警告(试图声明现有变量)。

如果您将其更改为var hello = null;,您将看到输出的更改。

现在,如果你有以下代码:

var hello = 'hello is assigned';
function prison() {
  console.log(hello);
  var hello;
  console.log(hello);
}
prison();

您将获得两个日志的undefined。这可能是由于变量提升-变量声明在执行前被移动到函数的开头-所以代码实际上看起来是这样的:

function prison() {
  var hello;
  console.log(hello);
  console.log(hello);
}

CCD_ 7在这两种情况下都是CCD_。

您的函数prison()在变量hello上有闭包,prison()中的var hello;没有创建新变量,该函数可以看到已经定义了一个全局变量hello,因此它使用该变量,因此您得到2个the hello argument

但是,如果在prison()之前没有定义hello,则会得到2个undefined bcoz,hello的定义将在prison()中被提升,并且hello没有设置值。