函數聲明和函數表達式
- 2020 年 6 月 2 日
- 筆記
- javascript, 原生js
函數聲明和函數表達式
一、函數聲明
語法
function name([param,[,param,[...,param]]]) {
[statements]
}
name: 函數名
param: 參數
statements: 函數體的語句
被函數聲明創造的函數是一個Function 對象,有Function對象的所有屬性、方法和行為
二、函數表達式
語法
let function_expression = function [name](param1[,param2[,...,paramN]]) {
statements
}
name: 函數名,可省略(匿名函數)。函數名只是函數體中的一個本地變量
param: 參數
statements: 函數語句
命名函數表達式。函數名作為函數作用域內的本地變量,可在函數內引用當前函數
let foo = function aa (num) {
num ++
if (num < 10) {
aa(num)
} else {
console.log(num, 'end')
}
}
foo(0) // 10 end
foo.name //aa
let bar = foo
bar === foo // true 指向同一地址
typeof aa // undefined 這個aa是變量,未聲明so
foo === aa // false 同上,aa為變量
區別
函數聲明提升
函數聲明被提升到了函數定義,可以在函數聲明前使用,函數表達式未提升,不可在聲明前使用
foo() // aha
function foo() {
console.log('aha')
}
bar() // 報錯 Uncaught TypeError: bar is not a function
var bar = function aa() {
console.log('bar')
}