和普通函数相比,箭头函数主要就是以下两个方面的特点
- 不绑定this,arguments
- 更简化的代码语法
第二个特点不需要过多赘述,下面我们来看看不绑定this和arguments这两个特点
么叫不绑定this,我个人的理解为箭头函数的this其实就是在定义的时候就确定好的,以后不管怎么调用这个箭头函数,箭头函数的this始终为定义时的this
我们还是以前面的那个setInterval代码为例
const Person = {
'name': 'little bear',
'age': 18,
'sayHello': function () {
setInterval(function () {
console.log('我叫' + this.name + '我今年' + this.age + '岁!')
}, 1000)
}
Person.sayHello()
3.2 不绑定arguments
箭头函数还有一个比较有特点的地方就是其不绑定arguments,即如果你在箭头函数中使用arguments参数不能得到想要的内容。
let arrowfunc = () => console.log(arguments.length)
arrowfunc()
//output
arguments is not defined
所以在箭头函数中我们是不能直接使用arguments对象的,但是如果我们又想获得函数的参数怎么办呢?
我们可以使用剩余参数来取代arguments剩余参数详情
let arrowfunc = (...theArgs) => console.log(theArgs.length)
arrowfunc(1,2)
//output
2
.2 不绑定arguments
箭头函数还有一个比较有特点的地方就是其不绑定arguments,即如果你在箭头函数中使用arguments参数不能得到想要的内容。
let arrowfunc = () => console.log(arguments.length)
arrowfunc()
//output
arguments is not defined
所以在箭头函数中我们是不能直接使用arguments对象的,但是如果我们又想获得函数的参数怎么办呢?
我们可以使用剩余参数来取代arguments剩余参数详情
let arrowfunc = (...theArgs) => console.log(theArgs.length)
arrowfunc(1,2)
//output
2
.2 不绑定arguments
箭头函数还有一个比较有特点的地方就是其不绑定arguments,即如果你在箭头函数中使用arguments参数不能得到想要的内容。
let arrowfunc = () => console.log(arguments.length)
arrowfunc()
//output
arguments is not defined
所以在箭头函数中我们是不能直接使用arguments对象的,但是如果我们又想获得函数的参数怎么办呢?
我们可以使用剩余参数来取代arguments剩余参数详情
let arrowfunc = (...theArgs) => console.log(theArgs.length)
arrowfunc(1,2)
//output
2
当Person.sayHello()去执行setInterval的时候,是在全局作用下执行的所有setInterval回调函数的this就为全局对象。es3-5中的函数this的值和调用这个函数的上下文有关。(注意是调用)
我们用箭头函数重写上诉函数
const Person = {
'name': 'little bear',
'age': 18,
'sayHello': () => {
setInterval(() => {
console.log('我叫' + this.name + '我今年' + this.age + '岁!')
}, 1000)
}
Person.sayHello()
大家猜猜结果是什么???
输出的是我叫'little bear',今年18岁嘛?
哈哈,太天真了,我开始也是这样想的,后面输出之后发现结果不对,输出的还是undefined。为什么呢??
因为我把方法写在了对象里,而对象的括号是不能封闭作用域的。所以此时的this还是指向全局对象。
所以,通过以上的错误可以提醒我们,最好不要用箭头函数作为对象的方法。
我们需要重新举一个例子,如下
function Person () {
this.name = 'little bear',
this.age = 18
let self = this
setInterval(function sayHello () {
console.log('我叫' + self.name + '我今年' + self.age + '岁!')
}, 1000)
}
let p = new Person()
缓存this,然后输出,能达到我们想要的结果。
把上述例子改为箭头函数的形式如下
function Person () {
this.name = 'little bear',
this.age = 18
setInterval(() => {
console.log('我叫' + this.name + '我今年' + this.age + '岁')
},1000)
}
let p = new Person()
我们可以看到,箭头函数使用了定义时上下文的this,且与在哪里调用没有关系。