正文
简介
JavaScript中的所有内容都发生在函数中。
函数是一个代码块,可以定义一次并随时运行。
函数可以选择接受参数,并返回一个值。
JavaScript中的函数是
对象
,一种特殊的对象:
函数对象
。
另外,函数被称为
第一类函数
,因为它们可以被赋值给一个值,它们可以作为参数传递并用作返回值。
句法
让我们从“旧的”,ES6 / ES2015之前的语法开始。这是一个
函数声明
:
function dosomething(foo) {
// do something
}
(现在,在ES6 / ES2015世界中,被称为
常规函数
)
函数可以分配给变量(这称为
函数表达式
):
const dosomething = function(foo) {
// do something
}
命名函数表达式
类似,但在堆栈调用跟踪中更好用,这在发生错误时很有用 - 它保存函数的名称:
const dosomething = function dosomething(foo) {
// do something
}
ES6 / ES2015引入了
箭头函数
,在使用内联函数时,特别适合用作参数或回调函数:
const dosomething = foo => {
//do something
}
箭头函数与上面的其他函数定义有很大的不同,我们稍后会解释。
参数
一个函数可以有一个或多个参数。
const dosomething = () => {
//do something
}
const dosomethingElse = foo => {
//do something
}
const dosomethingElseAgain = (foo, bar) => {
//do something
}
从ES6 / ES2015开始,函数可以具有参数的默认值:
const dosomething = (foo = 1, bar = 'hey') => {
//do something
}
这允许您在不填充所有参数的情况下调用函数:
dosomething(3)
dosomething()
ES2018引入了参数的尾随逗号,这个功能有助于减少因移动参数时丢失逗号而导致的错误(例如,移动中间的最后一个):
const dosomething = (foo = 1, bar = 'hey') => {
//do something
}
dosomething(2, 'ho!')
您可以将所有参数包装在一个数组中,并在调用函数时使用spread运算符:
const dosomething = (foo = 1, bar = 'hey') => {
//do something
}
const args = [2, 'ho!']
dosomething(...args)
当使用许多参数的时候,记住这些参数可能很困难。这里可以使用对象,解构保留参数名称:
const dosomething = ({ foo = 1, bar = 'hey' }) => {
//do something
console.log(foo) // 2
console.log(bar) // 'ho!'
}
const args = { foo: 2, bar: 'ho!' }
dosomething(args)
返回值
每个函数都返回一个值,默认情况下为“undefined”。
任何函数在其代码行结束时,或者当执行流找到
return
关键字时终止。
当JavaScript遇到此关键字时,它退出函数执行并将控制权交还给其调用者。
如果传递一个值,则该值将作为函数的结果返回:
const dosomething = () => {
return 'test'
}
const result = dosomething() // result === 'test'
您只能返回一个值。
要_模拟_返回多个值,您可以返回
对象文字
或
数组
,并在调用时使用
解构赋值
功能。
使用数组:
使用对象:
嵌套函数
可以在其他函数中定义函数:
const dosomething = () => {
const dosomethingelse = () => {}
dosomethingelse()
return 'test'
}
嵌套函数的作用域是外部函数,不能从外部调用。
对象方法
当用作对象属性时,函数称为方法:
const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log(Started)
}
}
car.start()
箭头函数中的
this
当箭头函数与常规函数用作对象方法时,有一个重要的行为。考虑这个例子:
const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log(Started ${this.brand} ${this.model})
},
stop: () => {
console.log(Stopped ${this.brand} ${this.model})
}
}
stop()
方法不能像你期望的那样工作。
这是因为
this
的处理在两个函数声明样式中是不同的。箭头函数中的
this
指的是封闭函数上下文,在本例中是
window
对象
this
,使用
function()
引用宿主对象
这意味着
箭头函数不适合用于对象方法
和构造函数(箭头函数构造函数实际上会在调用时引发
TypeError
)。
IIFE,立即调用函数表达式
IIFE是一个在声明后立即执行的功能:
;(function dosomething() {
console.log('executed')
})()
您可以将结果分配给变量: