Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

箭头函数 #24

Open
YBFACC opened this issue Jun 30, 2020 · 0 comments
Open

箭头函数 #24

YBFACC opened this issue Jun 30, 2020 · 0 comments

Comments

@YBFACC
Copy link
Owner

YBFACC commented Jun 30, 2020

箭头函数

箭头函数的介绍

箭头函数是es6的新特性。它对函数表达式进行缩写,可以使我们更优雅的使用函数进行编程。

以下是我们不使用箭头函数的例子:

let arr = [2, 3, 4, 1, 8]
arr.sort(function (a, b) {
  return a - b
})

下面我们将它改写:

let arr = [2, 3, 4, 1, 8]
arr.sort((a, b) => a - b)

代码不仅短了,而且行数也减少了。🚀

使用箭头函数

不需要参数

如果使用一个剪头函数时,你不需要参数,可以使用 () 代替。

let f = () => console.log(1)
f()

使用单个参数

使用单个参数时,可以省略括号。

let a = 1
let f = a => console.log(a)

f(a)

使用多参数

使用多个参数,参数需要在在括号内。

let a = 1,
  b = 2
let f = (a, b) => console.log(a + b)

f(a, b)

单条语句

在函数体中只有一条语句时,隐式的使用return:

let a = 1,
  b = 2
let f = (a, b) => a + b
//等价于以下代码
let g = (a, b) =>{return  a + b}
console.log(g(a, b))
console.log(f(a, b))

如果你不需要隐式的使用return,可以使用void返回undefeated。

let a = 1,
  b = 2

let g = (a, b) => void (a + b)
let f = (a, b) => a + b

console.log(g(a, b), f(a, b))

多条语句

需要你显式的调用return,不然返回的就是undefined。

let a = 1,
  b = 2

let g = (a, b) => {
  let c = 4
  return a + b + c
}
console.log(g(a, b))

注意事项

this的指向

箭头函数的this与声明所在的上下文相同。

在浏览器环境下执行以下代码:

var id = 'apple'
var obj = {
  id: 'obj',
  a: function () {
    console.log(this.id)
  },
  b: () => {
    console.log(this.id)
    return
  }
}

obj.a()
obj.b()

在箭头函数声明时,上下文环境是window。(用字面量创建的对象,环境参考上一级)

此代码在node环境下,表现不同。无法打印'apple'

原因:node当前文件的环境是 exports,需要微调下代码。

exports.id = 'apple'
var obj = {
  id: 'obj',
  a: function () {
    console.log(this.id)
  },
  b: () => {
    console.log(this.id)
    return
  }
}

obj.a()
obj.b()

这样就显示正确了。

不可以使用new构造对象

箭头函数本事就依靠声明时的this,还怎么new一个对象。😢

不可以使用arguments类数组

可以使用rest参数(...变量名)

不可以当作Generator函数

参考

ECMAScript 6 入门

《JavaScript忍者秘籍(第2版)》

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant