函数声明之函数提升

Javascript 中函数声明和函数表达式是存在区别的,函数声明在JS解析时进行函数提升,因此在同一个作用域内,不管函数声明在哪里定义,该函数都可以进行调用。而函数表达式的值是在JS运行时确定,并且在表达式赋值完成后,该函数才能调用。这个微小的区别,可能会导致JS代码出现意想不到的bug,让你陷入莫名的陷阱中。如下代码:

declaration()
function declaration() {
  console.log("declaration")
}
express()
var express = function () {
  console.log("express")
}

输出结果

declaration
/Users/zenglinquan/git/h5-cli/demo.js:125
express()
^
TypeError: express is not a function

以上两端代码其实等同于以下代码

function declaration() {
  console.log("declaration")
}
declaration()

var express;
express()
express= function () {
  console.log("express")
}

出现以上差异的原因是:
用函数声明创建的函数可以在函数解析后调用(解析时进行等逻辑处理);而用函数表达式创建的函数是在运行时进行赋值,且要等到表达式赋值完成后才能调用。其本质原因体现在这两种类型在Javascript function hoisting(函数提升)和运行时机(解析时/运行时)上的差异。

我们也可以通过打印两个函数的类型可以知道两者的不同

console.log(typeof declaration);
declaration()
function declaration() {
  console.log("declaration")
}

console.log(typeof express);
express()
var express= function () {
  console.log("express")
}

输出结果

function
declaration
undefined
/Users/zenglinquan/git/h5-cli/demo.js:128
express()
^
TypeError: express is not a function
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容