JavaScript 基础
Document
运算符
深入数据和类型
函数进阶
原型、继承
类
浏览器存储
Web API
事件
错误处理
异步编程
网络请求
模块
练习
实例
工具与规范
软件架构模式
设计模式
箭头函数
使用 =>
(箭头符号)也能定义一个函数,很多编程语言都支持这种写法, JavaScript 也不例外。这种写法被称为箭头函数。
下例是一个求和的箭头函数:
$$jsdemo$$
$$edit$$
let sum = (a, b) => {
return a + b
}
alert(sum(2, 5)) // 7
单行箭头函数
如果我们的箭头函数内部只有一行代码,那么可以简写成以下形式:
$$jsdemo$$
$$edit$$
let sum = (a, b) => a + b
alert(sum(2, 5)) // 7
单行箭头函数的运算结果会自动 return
,不用再写一个 return
语句。
箭头函数的 this 值
之前的章节学过,对象中的函数中的 this
值指向的是对象自身。
而如果这个方法使用的是箭头函数的写法,那么 this
值将是外部的 this
值,可以简单理解成对象所在上下文的 this
值。
$$jsdemo$$
$$edit$$
let mingren = {
name: "鸣人",
normal: function () {
console.log(this)
},
arrow: () => console.log(this),
}
mingren.normal() // {name: '鸣人', normal: ƒ, arrow: ƒ}
mingren.arrow() // window
console.log(this) // window
当我们把鸣人对象放到柯南中时,鸣人的箭头函数的 this
值等同于 getMr
的 this
值也就是柯南对象。
$$jsdemo$$
$$edit$$
let kenan = {
name: "柯南",
getMr: function () {
let mingren = {
name: "鸣人",
arrow: () => console.log(this),
}
return mingren
},
}
let mingren = kenan.getMr()
mingren.arrow() // {name: '柯南', getMr: ƒ}
练习
- 使用箭头函数改写以下常规函数。
function callFunction(func, arg) {
return func(arg)
}
function sayHello(message) {
alert(message)
}
callFunction(sayHello, "北京你好")
$$answer
$$jsdemo$$
$$edit$$
const callFunction = (func, arg) => {
return func(arg)
}
const sayHello = (message) => {
alert(message)
}
callFunction(sayHello, "北京你好")
$$
- 以下程序的输出结果是什么,为什么?
const mingren = {
name: "鸣人",
getWife() {
return {
name: "雏田",
getBrother: () => ({
name: "宁次",
getName: () => this.name,
}),
}
},
}
alert(mingren.getWife().getBrother().getName()) // 输出结果?
$$answer
$$jsdemo$$
$$edit$$
const mingren = {
name: "鸣人",
getWife() {
return {
name: "雏田",
getBrother: () => ({
name: "宁次",
getName: () => this.name,
}),
}
},
}
// 鸣人
// 因为 getName、getBrother 都是箭头函数,最终 this 指向 mingren
alert(mingren.getWife().getBrother().getName())
$$