1. 程式人生 > >js this 指向(es5)和es6箭頭函數this指向問題總結(鄒文豐版)

js this 指向(es5)和es6箭頭函數this指向問題總結(鄒文豐版)

一個 hat 登入 new this fun body 網上 情況

 本文純屬自己結合網上文章總結,有問題和不同想法歡迎留言指正
/********************簡單小例子********************/
var test =function () {
console.log(this);
};
// test(); //window
/*****************************2***********************************/
var test2 =function () {
console.log(this);
return function () {
console.log(this)
}
};
var bb={
a:‘1‘,
cc:test2 //賦值類型還未執行
};
// bb.cc()(); // 1.obj 2.window
/*****************************3***********************************/
var test3 =function () {
console.log(this);
return function () {
console.log(this)
}
};
var bb3={
a:‘1‘,
cc:test3() //默認在最外層執行
};
bb3.cc(); // 1.window 2.obj

//test2 tes3 只是一個括號的差別,決定指向的調用者;

/************普通函數例子*****************/
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth;
var that=this;
console.log(this); //this指向obj
return function () {
console.log(that);//that緩存保留在指向obj
console.log(this); //this指向window 最終的調用者不是obj而是window;
};
}
};
// obj.getAge()();//直接指向調用者“obj.getAge()”執行後就變成“()”而“()直接在最外層window上”

/************箭頭函數登入*****************/
var obj2 = {
name:‘obj2‘,
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
return () => {
var c=‘hehe‘;
console.log(this);//obj2
return () => {
console.log(this) //obj2 箭頭函數this始終指向最外層obj2;
}
}
}
};
// obj2.getAge()()();

//結合兩個例子箭頭函數的設計更加合理的,this始終保持指向定義時候的obj2,傳統的函數在這種情況就直接指向window,
// 個人感覺有點不合理,

/*************************普通構造函數***************************************/
function Fn(name,age){
this.name=name;
this.age=age;
console.log(this); //通過new一個實例之後this指向會指向這個對象
return function () {
console.log(this) //最終執行調用的還是window;不是new出來的對象
};
}
// var obj=new Fn(‘張飛‘,‘14‘); //this Fn
// obj(); //this window


/*******************箭頭構造函數*********************************************/
function Fn2(name,age){
this.name=name;
this.age=age;
console.log(this); //obj2
return () => {
console.log(this) //obj2
return () => {
console.log(this) //obj2
}
}
}
// var obj2=new Fn2(‘張飛‘,‘14‘); //this指向obj2
// obj2(); //this指向obj2

// Fn2()()();//如果構造函數直接當做普通函數來執行,那麽全部指向最初的window

//通過對比可以發現總結一下箭頭函數很好的解決了this原來在函數內部指向不合理的情況。你只要記住箭頭函數會繼承最初
//最外層定義的this

js this 指向(es5)和es6箭頭函數this指向問題總結(鄒文豐版)