• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
qiqi105
博客园    首页    新随笔    联系   管理    订阅  订阅

es5和es6中的this指向问题

const test ={
id:2,
a:function(){
var a_this=this;
setTimeout(function(){
console.log('a:',this,a_this)
})
},
a1:()=>{
var a1_this=this;
setTimeout(function(){
console.log('a1:',this,a1_this)
})
},
a11:()=>{
var a11_this=this;
setTimeout(()=>{
console.log('a11:',this,a11_this)
})
},
aa:function(){
var aa_this=this;
console.log('aa:',this,aa_this)
},
aa1:()=>{
var aa1_this=this;
console.log('aa1:',this,aa1_this)
}

}
test.a();
test.a1();
test.a11();
test.aa();
test.aa1();

 

const tests={
id:'tests',
a_tests:{
id:'a_tests',
a_tests_child:function(){
var a_tests_this = this;
console.log('a_tests_child:',this,a_tests_this)
},
a1_tests_child: () => {
var a1_tests_this = this;
console.log('a1_tests_child:',this,a1_tests_this)
},
a11_tests_child:{
a1111_tests_child:function(){
var a1111_tests_this = this;
console.log('a1111_tests_child:',this,a1111_tests_this)
},

a11112_tests_child: () => {
var a11112_tests_this = this;
console.log('a11112_tests_child:',this,a11112_tests_this)
}

}
}
}
tests.a_tests.a_tests_child();
tests.a_tests.a1_tests_child();
tests.a_tests.a11_tests_child.a1111_tests_child();
tests.a_tests.a11_tests_child.a11112_tests_child();

 

无论内部嵌套有多深,箭头函数this总是指向了window全局对象

posted @ 2018-06-14 10:04  qiqi105  阅读(225)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3