js---ES6 箭頭函式的this指向
阿新 • • 發佈:2018-11-12
普通函式的this指向看的是:
1.呼叫者
2.有沒有call/apply改變this指向
3.new改變AO中的this為一個空的物件
4.什麼都沒有,單純呼叫函式,this就是window,在自己的AO中。
箭頭函式的this指向:箭頭函式在定義時執行器上下文的this的指向(不具有塊級作用域),即會取當前的函式的作用域鏈上的this,忽略塊級作用域中的this
function haha(){ let Person = { 'name1': 'little bear', 'age': 18, 'sayHello': function () { console.log(this);//Person,以下為Person.sayHello的結果 var self = this; setTimeout(()=>{ console.log('我叫' + self.name1 + '我今年' + self.age + '歲!') }, 1000); //我叫little bear我今年18歲! setTimeout(()=>{ console.log('我叫' + this.name1 + '我今年' + this.age + '歲!') }, 1000);//我叫little bear我今年18歲! setTimeout(function(){ console.log('我叫' + this.name1 + '我今年' + this.age + '歲!') }, 1000);//我叫undefined我今年undefined歲! setTimeout(function(){ console.log('我叫' + self.name1 + '我今年' + self.age + '歲!') }, 1000);//我叫little bear我今年18歲! }, say:()=>{ console.log(this);//haha函式構造的空物件,如果不用haha函式包起來,那麼這個this是window } } // Person.sayHello();//this是Person //var sayHelloFun = Person.sayHello // sayHelloFun();//this是window Person.say(); // var say=Person.say; // say(); // localStorage.name1="anhe"; // sessionStorage.age=17; function ceshi(){ console.log(this);//ceshi構造的空物件 Person.say();//內部this是haha構造出來的物件,證明和呼叫位置無關,與定義位置的上下文中的this有關 } new ceshi(); } let xi= new haha();