箭头函数不使用this的四种标准规则(四种绑定规则见上上篇文章),也就是不绑定this,而是根据外层作用域来决定this.
var name="why"
var foo=()=>{
console.log(this)//箭头函数中的this作用域会向上一层找
}
foo()// window
var obj={foo:foo}
obj.foo()//obj绑不到this上 window
foo.call("abc")//abc绑不到this上 window
应用场景:
var obj={
data:[],
getData:function(){
//发送网络请求,将结果放到上面data属性中
//setTimeout(function()=>{
//var result=["abc","cba","nba"]
//this.data=result//这个this指向window
//},2000)
//在有箭头函数之前的解决方案(否则this指向window)
var _this=this;//obj对象
setTimeout(function()=>{
var result=["abc","cba","nba"]
_this.data=result//闭包
},2000)
}
setTimeout(()=>{//箭头函数不绑定this,this向上层作用域找,上层作用域的this即getData的this,getData调用时使用过obj调用的,意味着隐式绑定obj,因此this=obj
var result=["abc","cba","nba"]
_this.data=result
},2000)
}
obj.getData()