黄子涵

2 3.4 箭头函数不适用场景

了解了 ES6 箭头函数的优点,也看到了箭头函数的一些不足。那么在什么场景下不适合使用箭头函数呢?

1. 对象的方式

在对象的方法中不建议使用箭头函数,如果使用了会导致一些问题的产生,看下面这段代码。

示例23
const Hzh = {
    name: "黄子涵",
    age: '28',
    brother: "黄春钦",
    mother: "陈兰英",
    say: () => {
        setInterval(() => {
            console.log("你好!我是" + this.name + ",今年" + this.age + "岁啦!" + this.brother + "是我的弟弟," + this.mother + "是我的妈妈。");
        }, 1000)       
    }
}
Hzh.say();

查看示例 23 运行结果,如下图所示。

image

输出结果有问题,因为方法写在了对象里,而对象的括号是不能封闭作用域的,所以此时的 this 还是指向全局对象,而全局对象下没有 mame 和 age 属性,所以会出现问题。

2. 不能作为构造函数

由于箭头函数的 this 具有不绑定的特点,不能使用箭头函数作为构造函数,如果这样做了,也会报错。

3. 定义原型方法

定义原型方法时,也不推荐使用箭头函数,看下面这段代码 。

示例24
function Hzh () {
    this.name = "黄子涵",
    this.age = '28',
    this.brother = "黄春钦",
    this.mother = "陈兰英"
}

Hzh.prototype.say = () => {
    console.log(this.name);
    console.log(this.age);
    console.log(this.brother);
    console.log(this.mother);
}

var hcq = new Hzh();
hcq.say();

查看示例 24 运行结果,如下图所示。

[Running] node "e:\HMV\JavaScript\JavaScript.js"
undefined
undefined
undefined
undefined

[Done] exited with code=0 in 0.251 seconds

出现问题的原因是 this 指向 window 对象,这和使用箭头函数在对象中定义方法十分类似 。

小结

箭头函数由于代码的简洁性和不绑定调用者 this 的特点,在非方法函数中使用最合适,而在方法函数中使用,需要特别注意它的 this 绑定问题,如果需要动态地修改 this ,建议不要使用箭头函数。

posted @ 2022-06-09 14:59  黄子涵  阅读(54)  评论(0编辑  收藏  举报