箭头函数中的this

3,786 阅读2分钟

ES6中新增了箭头函数这种语法,箭头函数以其简洁性和方便获取this的特性。下面来总结一下他们之间的区别:

普通函数下的this:

  • 在普通函数中的this总是代表它的直接调用者,在默认情况下,this指的是window,
  • 在严格模式下,没有直接调用者的函数中的this是 undefined使用
  • call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象

箭头函数中的this:

  • 箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),
  • 而不是执行时的对象, 定义它的时候,可能环境是window,也有可能是其他的。
普通函数
function test() { 
   console.log(this);  
 }  
 test();  //window

test是一个全局函数,也就是挂载在window对象下的 test()等价于window.test();

var obj = {  
   func: function () {  
     console.log(this); 
     setTimeout(function () {   
       console.log(this);
     },0);   
   }  
 }  
 obj.func(); 
// obj,此时的this是obj对象    
// window

func的宿主环境是obj,所以func里面的this是obj。 定时器中的函数,由于没有默认的宿主对象,所以this指向window 严格模式下的this:

function test() {  
   'use strict';  
   console.log(this); 
 }  
 test(); 
 //undefined   
严格模式

在严格模式下,没有直接调用者的函数中的this是 undefined

"use strict";   
    var obj={   
      say:function(){   
        console.log(this);
      }  
    };  
obj.say();  
//obj    

有直接调用者的this是它的调用者

箭头函数
var obj = {  
   say: function () {  
     setTimeout(() => {  
       console.log(this);
     });  
   }  
 }  
 obj.say(); 
 // obj    

此时的 this继承自obj, 指的是定义它的对象obj, 而不是 window

var obj = {  
 say: function () {  
   var f1 = () => {  
     console.log(this); // obj  
     setTimeout(() => {  
       console.log(this); // obj  
     })  
   }  
   f1();  
 }  
}   
obj.say() 

因为f1定义时所处的函数 中的 this是指的 obj, setTimeout中的箭头函数this继承自f1,所以不管有多层嵌套,都是 obj

var obj = {  
 say: function () {  
   var f1 = function () {  
     console.log(this);  
     setTimeout(() => {  
       console.log(this); 
   })  
   };  
   f1();  
 }  
}  
obj.say()
// window, f1调用时,没有宿主对象,默认是window 
// window  

箭头函数没有this的绑定,必须通过查找作用链来决定其值。如果箭头函数被非箭头函数包含,则this绑定的是最近以层的非箭头函数的this;否则。this的值会被设置为undefined。 箭头函数在定义的时候它所处的环境相当于是window, 所以在箭头函数内部的this函数window