普通函数:this 永远指向调用它的对象,new的时候,指向new出来的对象。 //例1 var obj = { name: 'latency', sayName: function(){ console.log('name:',this.name); } } obj.sayName() //name: latency 例1:调用sayName()的是obj,所以this指向obj。 //例2 var name = 'cheng'; var obj = { name: 'latency', sayName: function(){ return function(){ console.log('name:',this.name); } } } obj.sayName()() //name: cheng 例2:obj调sayName方法后,返回的是一个闭包,而真正调这个闭包的是windows对象,所以其this指向window对象。 //例3 var obj = { name: 'latency', sayName: function(){ return () => { console.log('name:', this.name); } } } obj.sayName()() //name: latency 例3:箭头函数没有自己的 this,当在内部使用了 this时,它会指向最近一层作用域内的 this。因为有return所以出了sayName()当前作用域,所以它会指向最近一层作用域内的 this即obj。 //例4 var name = 'cheng'; var obj = { name: 'latency', sayName: () => { console.log('name:', this.name) } } obj.sayName() //name: cheng 例4:由于sayName()整个函数就是一个箭头函数,没有自己的this,所以this指向的最近一层作用域内的this,也就是window对象。这种情况下,就不适合用箭头函数来实现了。 //例5 var obj = { name: 'latency', sayName: function(){ return () => { return () => { return () => { console.log("name:", this.name); }; }; }; } } obj.sayName()()()() //name: latency 例5:自己练习吧! 参考链接:https://blog.csdn.net/latency_cheng/article/details/80022066
|
|