JavaScript Functions详解(包含ES6箭头函数)

1,506 阅读4分钟
原文链接: www.zcfy.cc

简介

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”。

Undefined return value

任何函数在其代码行结束时,或者当执行流找到return关键字时终止。

当JavaScript遇到此关键字时,它退出函数执行并将控制权交还给其调用者。

如果传递一个值,则该值将作为函数的结果返回:

const dosomething = () => {
  return 'test'
}
const result = dosomething() // result === 'test'


您只能返回一个值。

要_模拟_返回多个值,您可以返回对象文字数组,并在调用时使用解构赋值功能。

使用数组:

Destructuring using arrays

使用对象:

Destructuring using objects

嵌套函数

可以在其他函数中定义函数:

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()方法不能像你期望的那样工作。

Difference in arrow functions of this in methods

这是因为this的处理在两个函数声明样式中是不同的。箭头函数中的this指的是封闭函数上下文,在本例中是window对象

this points to the window object

this,使用function()引用宿主对象

这意味着箭头函数不适合用于对象方法和构造函数(箭头函数构造函数实际上会在调用时引发TypeError)。

IIFE,立即调用函数表达式

IIFE是一个在声明后立即执行的功能:

;(function dosomething() {
  console.log('executed')
})()


您可以将结果分配给变量:

const something = (function dosomething() {
  return 'something'
})()


它们非常方便,因为您无需在定义后单独调用该函数。

Function 挂载

执行代码之前的JavaScript会根据某些规则对其进行重新排序。

会将函数移动到其范围的顶部。这就是下面例子不会报错的原因;

dosomething()
function dosomething() {
  console.log('did something')
}


Hoisting example

在内部,JavaScript在调用之前移动函数,以及在同一范围内找到的所有其他函数:

function dosomething() {
  console.log('did something')
}
dosomething()


现在,如果你使用命名函数表达式,因为你正在使用变量,会发生不同的事情。变量声明被提升,但不是值,因此不是函数。

dosomething()
const dosomething = function dosomething() {
  console.log('did something')
}


不会工作:

Hoisting named functions

这是因为内部发生的事情是:

const dosomething
dosomething()
dosomething = function dosomething() {
  console.log('did something')
}


“let”声明也是如此。var声明也不起作用,但是报的不是同样的错误:

Hoisting var declarations

这是因为var声明被提升并用undefined作为值初始化,而constlet被提升但未初始化。