JavaScript提升函数与函数变量 [英] JavaScript hoisting function vs function variable
本文介绍了JavaScript提升函数与函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的javascript代码:
Here is my javascript code :
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未定义的错误。
My question is regarding why c() and b() behaving differently. And b should throw error something like b is not defined.
推荐答案
功能声明将与其正文一起提升。
函数表达式不会,只会挂起var语句。
这是你的代码在编译时之后看起来对解释器的看法 - 在运行时之前:
A Function Declaration will be hoisted along with its body.
A Function Expression not, only the var statement will be hoisted.
This is how your code "looks" like to the interpreter after compiletime - before runtime:
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
KISSJavaScript
这篇关于JavaScript提升函数与函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文