箭头函数

使用 => (箭头符号)也能定义一个函数,很多编程语言都支持这种写法, 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 值等同于 getMrthis 值也就是柯南对象。

$$jsdemo$$
$$edit$$
let kenan = {
    name: "柯南",
    getMr: function () {
        let mingren = {
            name: "鸣人",
            arrow: () => console.log(this),
        }

        return mingren
    },
}

let mingren = kenan.getMr()
mingren.arrow() // {name: '柯南', getMr: ƒ}

练习

  1. 使用箭头函数改写以下常规函数。
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, "北京你好")

$$

  1. 以下程序的输出结果是什么,为什么?
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())

$$