以下是我的javascript代码:
console.log(a);
c();
b();
var a = 'Hello World';
var b = function(){
console.log("B is called");
}
function c(){
console.log("C is called");
}下面是输出:
undefined
hoisting.html:12 C is called
hoisting.html:6 Uncaught TypeError: b is not a function我的问题是为什么c()和b()的行为不同。而b应该抛出错误,类似于b是没有定义的。
发布于 2016-02-07 12:33:06
“功能宣言”将与其身体一起悬挂。
函数表达式不是,只有var语句才会被吊起。
在编译时之后--运行时之前--您的代码在解释器中的“外观”就是这样的:
var c = function c(){
console.log("C is called");
}
var a = undefined
var b = undefined
console.log(a); // undefined at this point
c(); // can be called since it has been hoisted completely
b(); // undefined at this point (error)
a = 'Hello World';
b = function(){
console.log("B is called");
}KISSJavaScript
发布于 2016-02-07 12:24:51
发布于 2016-02-07 12:26:57
在您调用b时,还没有定义。您的b是一个包含函数的变量,访问b的时间尚未定义。
https://stackoverflow.com/questions/35253376
复制相似问题