箭头函数:
箭头函数相当于匿名函数,并且简化了函数定义。
箭头函数中的this:
箭头函数中的this是在定义函数的时候绑定,而不是在执行函数的时候绑定。
箭头函数中,this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this绑定,导致内部的this绑定就是外层代码块的this(需要查找作用域链)。正式因为它没有this绑定,所以也就不能用作构造函数。
例:
注:请参考上例正确理解外部代码块的意思。所谓定义时绑定,就是this是继承自父执行上下文中的this。
箭头函数的使用时机
1、如果有一个简短的语句,返回的是一个简单表达式,函数内不没有this引用,也没有自身的引用(递归)
2、内部需要使用var self = this 或者使用bind(),可适合改用箭头函数
3、大部分的回调函数使用箭头函数
this.name = 'aa'
this.say = function () {
console.log(`this is my name ${this.name}`)
}
this.say = this.say.bind(this)
// this.say = () => {
// console.log(`this is my name ${this.name}`)
// }
}
let person1 = new Person()
let res = person1.say
res()