ES5寫法:
var obj ={
x:1,
? ? func:function(){
console.log(this.x);
? ? },
? ? test:function(){
? ? ? ?var that= this;
? ? ? ? //setTimeout是異步漏隐,函數(shù)已經(jīng)執(zhí)行完成括蝠,this指向的值是windows郁季;
? ? ? ? setTimeout(function(){
alert(that);
? ? ? ? ? ? console.log(that.func());
? ? ? ? },10)
}
}
ES6寫法:
var obj = {
x:1,
? ? func:function(){
console.log(this.x);
? ? },
? ? test:function(){
setTimeout(()=>{
alert(this);
? ? ? ? ? ? alert(this.func());
? ? ? ? },10)
}
}
obj.test()
ES6的優(yōu)點(diǎn):(相對ES5)
1惶看、精簡
2者铜、避免了調(diào)用異步函數(shù)時(shí)對this的志向不同柒莉。
3祭隔、待定