其他分享
首页 > 其他分享> > 2.3.3 和普通函数的区别

2.3.3 和普通函数的区别

作者:互联网

与普通函数相比,箭头函数的优势主要表现在以下两个方面:

  • 不绑定 this、arguments
  • 更简化的代码语法

第二个特点不需要过多赘述,主要讲解不绑定 this 和 arguments 这两个特点。

1.不绑定 this

不绑定 this 可以理解为箭头函数的 this 在定义的时候就确定了,以后不管如何调用箭头函数,箭头函数的 this 始终为定义时的 this。现在使用箭头函数来改写示例 18 。

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

let hzh = new Hzh();

image

2. 不绑定 arguments

箭头函数还有一点需要注意:不绑定 arguments,即如果在箭头函数中使用 arguments 参数是会出现一些问题的。看下面这段代码,需求是打印出 arguments 参数的长度。

示例21
let hzh = () => console.log(arguments.length);
hzh();
[Running] node "e:\HMV\JavaScript\JavaScript.js"
5

[Done] exited with code=0 in 0.246 seconds

这里的运行结果和书上的不一样

image

所以在箭头函数中不能直接使用 arguments 对象,如果需要获得函数的参数又该怎么办呢?可以使用剩余参数来取代 arguments。

提示

剩余参数语法允许将不确定数量的参数表示为数组。

示例22

let hzh = (...theArgs) => console.log(theArgs.length);
hzh(1,2);
[Running] node "e:\HMV\JavaScript\JavaScript.js"
2

[Done] exited with code=0 in 0.178 seconds

标签:示例,函数,区别,绑定,hzh,箭头,arguments,2.3
来源: https://www.cnblogs.com/Huang-zihan/p/16358908.html