javaScript中this指向

普通函數調用

console.log(this)	//Window
	var aa = {
		name:"aa",
		fun: function(){
			console.log(this)//{name: "aa", fun: ƒ}
		}
	}
	aa.fun()

第一個打印輸出語句是由window對象直接調用,所以this指向window,第二個是由aa對象直接調用,所以this指向aa。

var aa = {
		name:"aa",
		fun: function(){
			function f(){
				console.log(this)	//window
			}
			f()
		}
	}
	aa.fun()

與上一個不同的是,在fun函數中嵌套了一個f()函數,當我同樣使用aa.fun去調用時,this指向window.這是因爲f函數是在fun函數中,是屬於普通函數調用,並沒用通過aa對象直接調用,而是自執行,這時候f就屬於全局函數

var aa = {
		name:"aa",
		fun: function(){
			return function (){
				console.log(this)	//window
			}
		}
	}
	aa.fun()()

在此情況下,aa.fun()是一個普通函數,而我們在調用時,是由window對象直接調用的,所以此時this指向window

var aa = {
		name:"aa",
		fun: function(){
			// console.log(this)//{name: "aa", fun: ƒ}
			function f(){
				console.log(this)
			}
			f.bind(this)()	//{name: "aa", fun: ƒ}
			f.apply(this)	//{name: "aa", fun: ƒ}
			f.call(this)	//{name: "aa", fun: ƒ}
		}
	}
	aa.fun()

在函數調用時,可以使用bind/call/apply來改變this指向,其中bind返回一個函數,而call和aply是返回一個對象
回調函數

function cc(){
		console.log(this)	//window
	}
	var bb = {
		name:"bb",
		fun:function (callback){
			console.log(this)	//object {name:bb,fun:f}
			callback()
		}
	}
	bb.fun(cc)

這是一個回調函數,主函數爲bb(),回調函數爲cc(),當主函數執行完成後,執行回調函數,回調函數中,默認this指向window,因爲本質上是在函數內callback,並不是由對象直接調用
箭頭函數

var dd = {
		name:"dd",
		fun:function(){
			console.log(this)	//{name: "dd", fun: ƒ, ee: ƒ}
			var f1= ()=>{
				console.log(this)	//{name: "dd", fun: ƒ, ee: ƒ}
			}
			f1()
		},
		ee:()=>{
			console.log(this)	//window
		}
	}
	dd.ee()
	dd.fun()

箭頭函數中是沒有this的,所以箭頭函數中的this是繼承上層作用域中的this
ee是一個函數,這個函數內部的this等同於上層作用域中this指向,而dd.ee()是由window對象直接調用的,所以這裏的this指向window (官方解釋:this指向定義時的this,而不是使用時的this)
f1是fun函數內的一個函數,當調用fun函數時,會調用f1函數,所以f1函數內this繼承fun函數內this,也就指向了dd對象。利用這一點,以後可以用箭頭函數來改變this指向。
構造函數

function gg(){
		var name="gg"
		this.fun=function(){
			console.log(this)	//gg {fun: ƒ}
		}
		console.log(this.name)	//undefined
		console.log(this)	//gg {fun: ƒ}
	}
	var obj = new gg()
	obj.fun()

首先構造函數創建一個新對象,然後將作用域賦給這個新對象,這時函數中this就指向了這個新對象,使用new創建的是一個空對象,然後使用this來初始化新創建的對象的屬性,這也就是爲什麼this.name=undefined,因爲他並沒有被初始化,所以在調用fun方法時,this就指向這個對象。
setTimeOut和setInterval函數

setTimeout(()=>{
		console.log(this)	//window
	},0)
	setInterval(function (){
		console.log(this)	//window
	},1000)

這兩個函數都是window對象下的函數,是由window對象直接調用,所以他們內部的this一般直接指向window

就先到這裏吧!以後有更多瞭解再更新。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章