ES6 箭头函数
1.最简单的箭头函数
定义
let f = v => v
使用
console.log( f(1) )
输出
1
1.1.等同于创建函数方法
function f (v) {
return v
}
let f = function (v) {
return v
}
1.2.箭头函数不需要参数
定义
let f = () => 5
等同于
function f () {
return 5
}
等同于
let f = function () {
return 5
}
使用
console.log( f() )
1.3.箭头函数多参数
定义
let sum = (a, b) => a + b
等同于
function sum (a, b) {
return a + b
}
等同于
let sum = function (a, b) {
return a + b
}
使用
console.log( sum(1, 2) )
2.箭头函数与结构函数
定义
let full = ({first, last}) => first + ' ' + last
使用1:
console.log( full({first: "muzico", last: "liang"}) )
使用2:
let people = {
first: "muzico",
last: "liang"
}
console.log( full(people) )
该箭头函数等同于
function full ({first, last}) {
return first + ' ' + last
}
或等同于
var people = {first:"",last:""}
function full (people) {
return people.first + ' ' + people.last
}
3.箭头函数返回一个对象
花括号被解析为代码块,所以箭头函数返回一个对象时,需要在对象外面加上括号。
代码1:
let f = () => ({name: "muzico"})
console.log( f() );
console.log( f().name );
输出:
{ name: 'muzico' }
muzico
代码2:
let f = id => ({id: id, name: "muzico"})
console.log( f(10) )
console.log( f(10).id )
console.log( f(10).name )
输出:
{ id: 10, name: 'muzico' }
10
muzico
4.简化回调函数
4.1.例子:
let res = [1,2,3].map(function (x) {
return x * x
})
console.log(res);
输出:
[ 1, 4, 9 ]
箭头函数的写法:
let res = [1,2,3].map(x => x * x)
4.2.例子:
let res = [2,3,1].sort(function (a, b) {
return a - b
})
console.log(res);
输出:
[ 1, 2, 3 ]
箭头函数的写法:
let res = [2,3,1].sort((a, b) => a - b)
5.箭头函数与参数结合
5.1.例子:
定义
const numbers = (...nums) => nums
使用
console.log( numbers(1,2,3,4,5) );
输出
[ 1, 2, 3, 4, 5 ]
5.2.例子:
定义
const headAndTail = (head, ...tail) => [head, tail]
使用
console.log( headAndTail(1,2,3,4,5) );
输出
[ 1, [ 2, 3, 4, 5 ] ]
6.this 固化
在箭头函数中,this 是被固化的,就是说this在定义函数的时候就已经被绑定,不能修改,也和调用者无关。
普通函数:
let teacher = {
name:"muzico",
age:18,
print:function () {
console.log(this.name,this.age)
}
}
let student = {
name:"ami",
age:16,
print:teacher.print
}
teacher.print()
student.print()
输出:
muzico 18
ami 16
箭头函数:
let teacher = {
name:"muzico",
age:18,
print: (name) => {
console.log(this.name, this.age)
}
}
let student = {
name:"ami",
age:16,
print:teacher.print
}
teacher.print()
student.print()
输出:
undefined undefined
undefined undefined
测试 箭头函数中的 this是否指向全局对象
this.name = "aaa"
let teacher = {
name:"muzico",
age:18,
print: (name) => {
console.log(this.name, this.age)
}
}
let student = {
name:"ami",
age:16,
print:teacher.print
}
teacher.print()
student.print()
输出:
aaa undefined
aaa undefined
的确,指向了全局对象。
测试 箭头函数中的 this指向,被固化,不能被修改
function foo () {
this.name = "foo"
this.inline = () => {
console.log(this.name)
}
this.outline = function () {
console.log(this.name)
}
}
let obj = new foo()
obj.inline()//foo
obj.inline.call({name:"muzico"})//foo
obj.outline()//foo
obj.outline.call({name:"muzico"})//muzico
箭头函数在定义时,this就固化为 foo 函数对象本身,无论调用方如何修改,这个this 指向都不变。
即使更改成下面的代码也是无法改变的。
function foo () {
let _this = this
this.name = "foo"
this.inline = () => {
console.log(_this.name)
}
this.outline = function () {
console.log(this.name)
}
}