/** 一、全局環(huán)境下*/
// console.log(this == window)
// 嚴(yán)格模式下普通function的this為undefined
// 非嚴(yán)格模式下, this默認(rèn)指向全局對象window
// function f2(){
// ? ? return this
// }
// console.log(f2()===window)
/** 二撵术、對象中的this
?* 對象內(nèi)部方法的this指向調(diào)用這些方法的對象
?* 1.函數(shù)的定義位置不影響其this指向,this指向只和調(diào)用函數(shù)的對象有關(guān)
?* 2.多層嵌套的對象链快,內(nèi)部方法的this指向離被調(diào)用函數(shù)最近的對象(window也是對象险领,其內(nèi)部對象調(diào)用方法的this指向內(nèi)部對象,而非window)*/
// var obj = {
// ? ? prop: 34,
// ? ? show: function () {
// ? ? ? ? console.log(this)
// ? ? ? ? console.log(this.prop)
// ? ? ? ? return this
// ? ? }
// }
// const objRes = obj.show()
// console.log(objRes === obj)
// // 從上面調(diào)用的例子來看戒职, obj 調(diào)用了 show方法栗恩,故 show方法內(nèi)部的this指向obj,即對象內(nèi)部的普通function 誰調(diào)用洪燥,this就指向誰(window可視為一個大對象磕秤,故也是如此)
/** 三、原型鏈中this
?* ?原型鏈中方法的this仍然指向調(diào)用它的對象捧韵,與二 一致
*/
// var obj = {
// ? ? show: function(){
// ? ? ? ? console.log(this)
// ? ? ? ? console.log(this.a + this.b)
// ? ? }
// }
// var newObj = Object.create(obj)
// newObj.a = 2
// newObj.b = 4
// console.log(newObj.show())
// //{ a: 2, b: 4 }
// //6
// // 輸出結(jié)果如上市咆,因?yàn)镺bject.create()是以目標(biāo)對象作為新創(chuàng)建的對象的__proto__
/** 四、setTimeout & setInterval
?* ?對于延時函數(shù)內(nèi)部的回調(diào)函數(shù)的this指向全局對象window(只對于普通函數(shù)再来,箭頭函數(shù)除外蒙兰,也可以通過bind改變其內(nèi)部函數(shù)的this指向)
?*/
// function Person (){
// ? ? this.age = 18
// ? ? setTimeout(function(){
// ? ? ? ? console.log(this)
// ? ? ? ? console.log(this.age)
// ? ? }, 3000)
// }
// function Person (){
// ? ? this.age = 18
// ? ? setTimeout((function(){
// ? ? ? ? console.log(this)
// ? ? ? ? console.log(this.age)
// ? ? }).bind(this), 3000)
// }
// var p = new Person()
/** 五、箭頭函數(shù)的this
?* ?箭頭函數(shù)不綁定this芒篷, 它會捕捉其所在(即定義的位置)上下文的this值搜变,作為自己的this值
?* ?1. 所以call()/apply()/bind() 方法對于箭頭函數(shù)來說只是傳入?yún)?shù),對它的this毫無影響
?* ?2. 考慮到this是詞法層面上的针炉,嚴(yán)格模式與this相關(guān)的規(guī)則都降被忽略
*/
// function Person (){
// ? ? const that = this
// ? ? this.age = 18
// ? ? setTimeout(()=>{
// ? ? ? ? console.log(this)
// ? ? ? ? console.log(this.age)
// ? ? ? ? console.log(that === this)
// ? ? ? ? function showAge(){
// ? ? ? ? ? ? console.log("========", this)
// ? ? ? ? ? ? console.log("========", this.age, that.age)
// ? ? ? ? }
// ? ? ? ? showAge()
// ? ? }, 3000)
// }
// var p = new Person()
/** 六挠他、在函數(shù)沒有任何對象調(diào)用時,this默認(rèn)指向window(非嚴(yán)格模式下篡帕,嚴(yán)格模式下為undefined)
?* ?例子如上面殖侵, showAge() this指向window
*/