gpt4 book ai didi

javascript - 这些示例中的 javascript 变量 "hoisted"如何来自 MDN

转载 作者:搜寻专家 更新时间:2023-11-01 05:24:25 25 4
gpt4 key购买 nike

this mozilla 文章,我读过:

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined.

然后是一些例子:

/**
* Example 1
*/
console.log(x === undefined); // logs "true"
var x = 3;


/**
* Example 2
*/
// will return a value of undefined
var myvar = "my value";

(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();

Example 2, above, will be interpreted the same as:

var myvar = "my value";

(function() {
var myvar;
console.log(myvar); // undefined
myvar = "local value";
})();

我没有看到任何东西被“提升”——至少在我传统上解释这个词的定义的意义上没有:变量似乎是 undefined 直到它们被声明。在什么意义上可以“引用稍后声明的变量”?

最佳答案

当您使用 var 时,它被“提升”到函数声明的顶部。我们再来看第二个例子:

var myvar = "my value";

(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();

注意 var myvar = 'my value' 首先是如何声明的。接下来,在函数范围内,调用 console.log(myvar)。结果是“未定义”。为什么?您会认为这将是“我的值(value)”,因为这是代码的顺序。

因为函数作用域中的局部变量 var myvar 被提升了,所以没有定义。这本质上等同于像这样编写函数:

(function() {
var myvar;
console.log(myvar); // undefined
myvar = "local value";
})();

关于javascript - 这些示例中的 javascript 变量 "hoisted"如何来自 MDN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14806135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com