箭頭函數中的this指向的是定義時的this函數
demo:this
var demo=function(){ this.a='a'; this.b='b'; this.c={a:'a+',b:function(){reurn this.a}} } var demo1=function(){ this.a='a'; this.b='b'; this.c={a:'a+',b:()=> this.a} } console.log(new demo().c.b())//a+// 普通函數this指向調用方的this console.log(new demo1().c.b())//a//箭頭函數,this指向定義時的this
箭頭函數不能做爲構造函數,不能使用new命令,不然會拋出一個錯誤spa
不能使用arguments對象code
不能使用yield命令對象
class Person{ constructor(){ this.name="zhangsan"; } say(msg){ setTimeout(function(){ console.log(this);//window console.log(msg+" "+this.name);//hello undefined },1000); } } var person=new Person(); person.say('hello');
超時調用的代碼都是在全局做用域中執行的,所以無論函數在哪兒,其中的this在非嚴格模式下指向window對象,在嚴格模式下是undefinedblog
使用箭頭函數定義作用域
class Person{ constructor(){ this.name="zhangsan"; } say(msg){ setTimeout(()=>{ console.log(this);//person console.log(msg+" "+this.name);//hello zhangsan },1000); } } var person=new Person(); person.say('hello');