[英]Execution context and the execution context object in Javascript
我的头在旋转,有人可以解释一下javascript如何存储变量以及什么是“执行上下文”和“执行上下文对象”吗?
为什么该代码段在控制台上显示以下输出:
你好论点
你好论点
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);
}
在这两种情况下, hello
undefined
。
您的函数prison()
对变量hello
, var hello;
具有闭包var hello;
在prison()
中没有创建新变量,该函数可以看到已经定义了一个全局变量hello
因此它使用该变量,因此您得到2 the hello argument
然而,如果没有hello
之前定义的prison()
你会得到2 undefined
bcoz的定义hello
会在被吊起prison()
和hello
有没有值设置为它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.