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全局对象