这个问题在这里已经有了答案:
Need to understand Javascript function hoisting example
(5 个回答)
6年前关闭。
对于需要提供 Javascript 的顺序(或者至少是执行 JavaScript 的顺序),我感到非常困惑。所以,我创建了一些代码来证明我的困惑。
考虑以下
var i = 5;
alert(i); //shows 5
alert(k); //shows undefined
var k = 10;
我理解这样做的原因(或者我认为)。我们可以看到
k
尚未创建!那么,怎么样
function DoThis() {
var x = "hello";
alert(x);
}
DoThis(); //shows the value "bye"
function DoThis() {
var x = "bye";
alert(x);
}
这令人困惑......第一个例子的逻辑似乎不再适用。
为什么 Javascript 显示值 "bye"而不是我期望的 "Hello"?
JSFIDDLE
最佳答案
Function declarations are hoisted在javascript中(另见the MDN on hoisting)。
您的第二个代码相当于
var DoThis = function() {
var x = "hello";
alert(x);
}
DoThis = function () {
var x = "bye";
alert(x);
}
DoThis(); //shows the value "bye"
这仅适用于
function name(){...
声明。如果您将函数声明为var DoThis = function() {
var x = "hello";
alert(x);
}
DoThis(); //shows the value "hello"
var DoThis = function () {
var x = "bye";
alert(x);
}
然后只有 var 声明和 不是分配被吊起。这意味着将使用第一个函数值(使用之前的那个)。
关于javascript - javascript如何在页面上执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31430112/