JavaScript documentation状态:
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.
现在在我的代码中(实际上这是来自 W3Schools 的同一主题的代码片段)我没有使用函数:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript index</title>
</head>
<body>
<p id="demo"></p>
<script>
x = 5; // Assign 5 to x
elem = document.getElementById( "demo" ); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
alert( x );
</script>
</body>
</html>
alert()
的结果是5。为什么不是undefined
。根据我的理解,var x
行应该提升到顶部,alert()
应该显示undefined
。
我从以下位置阅读了更多相关内容:http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092
我没有得到什么?
最佳答案
您的 var x
语句已提升到顶部。因此,对 x
的赋值发生在声明之后、alert()
之前。
链接引用中可能会让您失望的示例代码是这样的:
var myvar = 'my value';
(function() {
alert(myvar); // undefined
var myvar = 'local value';
})();
该示例与您的示例在本质上有所不同:所涉及变量的初始化发生在alert()
之后,而不是之前。当 var 声明被提升时,唯一被提升的部分是声明本身,而不是初始化。上面的那个小函数被解释为好像是这样写的:
var myvar = 'my value';
(function() {
var myvar;
alert(myvar); // undefined
myvar = 'local value';
})();
您的代码在顶部有 x = 5
,因此情况不同。
关于JavaScript 没有函数的变量提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28160866/