箭头函数写法:
ES5 函数传统写法:
function al(x){
alert(x)}
al("ok")
ES6 使用箭头函数写法:
匿名函数:
()=>"ok" //不带参数.return 被简写。等价于function(){return "ok"}
//如果函数比较复杂,则外面需要 { } 包裹
(x)=>{alert(x)} //带参数
具名函数:
al=(x) => {alert(x)}
al("ok我是箭头函数") //调用函数
function(i){ return i + 1; } //ES5
(i) => i + 1 //ES6
箭头函数的 this 用法:
用来解决 this 作用域的问题。传统的函数写法,存在this 作用域问题。函数的this 作用域,指向全局 window
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //undefined says hi
运行上面的代码会报错,这是因为setTimeout
中的this
指向的是全局对象。所以为了让它能够正确的运行,传统的解决方法有两种:
第一种是将this传给self,再用self来指代this
class Animal {
constructor(){
this.type = 'animal'
self=this //用self 保存当前对象的this
}
says(say){
setTimeout(function(){
console.log(self.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says("ok")
第二种方法是用bind(this),即
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}.bind(this), 1000)
使用箭头函数解决 this 作用域的问题
但现在我们有了箭头函数,就不需要这么麻烦了:
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //animal says hi
当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
PS: 因为对象中的this,指向对象本身;而函数中的this,指向的是全局 window 对象
参考:JS 中的 this 指向 https://blog.csdn.net/weixin_41796631/article/details/89109897