在 Java 等面向?qū)ο蟮恼Z(yǔ)言中融欧,this 關(guān)鍵字的含義是明確且具體的,即指代當(dāng)前對(duì)象盯孙。一般在編譯期綁定鲁森。而 在 JavaScript 中,this 是動(dòng)態(tài)綁定振惰,或稱為運(yùn)行期綁定的 歌溉,由于其運(yùn)行期綁定的特性,JavaScript 中的 this 含義要豐富得多,它可以是全局對(duì)象痛垛、當(dāng)前對(duì)象或者任意對(duì)象草慧,這完全取決于函數(shù)的調(diào)用方式。
Q1:為什么要用this
呢匙头?
function identify(){
return this.name.toUpperCase();
}
function speak(){
var greeting = "Hello漫谷,I'm " + identify.call(this);
console.log(greeting);
}
var me = { name: 'BubbleM', speak: speak };
me.speak(); // Hello,I'm BUBBLEM
上面這段代碼可以在不同的上下文對(duì)象(me和you)中重復(fù)使用函數(shù)identify和speak蹂析,不用針對(duì)每個(gè)對(duì)象編寫(xiě)不同版本的函數(shù)舔示。
如果不使用this,那就需要給identify和speak顯式傳入一個(gè)上下文對(duì)象:
function identify(context){
return context.name.toUpperCase();
}
function speak(context){
var greeting = "Hello识窿,I'm " + identify(context);
console.log(greeting);
}
var me = { name: 'BubbleM', speak: speak };
me.speak(me); // Hello,I'm BUBBLEM
A1:this提供了一種更優(yōu)雅的方式來(lái)隱式“傳遞”一個(gè)對(duì)象引用脑融,因此可以將API設(shè)計(jì)得更加簡(jiǎn)潔并易于復(fù)用喻频。
this指向誰(shuí)?
多數(shù)情況下肘迎,this 指向調(diào)用它所在方法的那個(gè)對(duì)象甥温。當(dāng)調(diào)用方法沒(méi)有明確對(duì)象時(shí),this 就指向全局對(duì)象妓布。在瀏覽器中姻蚓,指向 window;在 Node 中匣沼,指向 Global狰挡。(嚴(yán)格模式下,指向 undefined)
?? this 的指向是在調(diào)用時(shí)決定的释涛,而不是在書(shū)寫(xiě)時(shí)決定的加叁。這點(diǎn)和閉包恰恰相反。
// 聲明位置
var me = {
name: 'xiuyan',
hello: function() {
console.log(`你好唇撬,我是${this.name}`)
}
}
var you = {
name: 'xiaoming',
hello: function() {
var targetFunc = me.hello
targetFunc()
}
}
var name = 'BigBear'
// 調(diào)用位置
you.hello()
調(diào)用位置輸出的結(jié)果是 BigBear—— 竟然不是 xiaoming它匕?的確,我們打眼看過(guò)去窖认,直覺(jué)上肯定會(huì)認(rèn)為是 you 這個(gè)對(duì)象在調(diào)用 hello 方法豫柬、進(jìn)而調(diào)用 targetFunc,所以此時(shí) this 肯定指向 you 對(duì)象捌私烧给!為啥會(huì)輸出一個(gè) window 上的 name 呢?
“this 指向調(diào)用它所在方法的那個(gè)對(duì)象”
回頭看 targetFunc 這個(gè)方法喝噪,之所以第一直覺(jué)會(huì)認(rèn)為它的 this 應(yīng)該指向 you 這個(gè)對(duì)象创夜,其實(shí)還是因?yàn)榘?“聲明位置” 和 “調(diào)用位置” 混淆了。我們看到雖然 targetFunc 是在 you 對(duì)象的 hello 方法里聲明的仙逻,但是在調(diào)用它的時(shí)候驰吓,我們是不是沒(méi)有給 targetFunc 指明任何一個(gè)對(duì)象作為它前綴涧尿? 所以 you 對(duì)象的 this 并不會(huì)神奇地自動(dòng)傳入 targetFunc 里,js 引擎仍然會(huì)認(rèn)為 targetFunc 是一個(gè)掛載在 window 上的方法檬贰,進(jìn)而把 this 指向 window 對(duì)象姑廉。
一定要記住“不管方法被書(shū)寫(xiě)在哪個(gè)位置,它的 this 只會(huì)跟著它的調(diào)用方走”這個(gè)核心原則翁涤。
特殊情境下的this指向
在三種特殊情境下桥言,this 會(huì) 100% 指向 window:
- 立即執(zhí)行函數(shù)(IIFE),即定義后立刻調(diào)用的匿名函數(shù)葵礼;
var name = 'BigBear'
var me = {
name: 'xiuyan',
// 聲明位置
sayHello: function() {
console.log(`你好号阿,我是${this.name}`)
},
hello: function() {
(function(cb) {
// 調(diào)用位置
cb()
})(this.sayHello)
}
}
me.hello() // BigBear
立即執(zhí)行函數(shù)作為一個(gè)匿名函數(shù),在被調(diào)用的時(shí)候鸳粉,我們往往就是直接調(diào)用扔涧,而不會(huì)(也無(wú)法)通過(guò)屬性訪問(wèn)器( 即 xx.xxx) 這樣的形式來(lái)給它指定一個(gè)所在對(duì)象,所以它的 this 是非常確定的届谈,就是默認(rèn)的全局對(duì)象 window枯夜。
- setTimeout 中傳入的函數(shù);
- setInterval 中傳入的函數(shù)艰山;
var name = 'BigBear'
var me = {
name: 'xiuyan',
hello: function() {
setTimeout(function() {
console.log(`你好湖雹,我是${this.name}`)
})
}
}
me.hello() // 你好,我是BigBear
我們所看到的延時(shí)效果(setTimeout)和定時(shí)效果(setInterval)曙搬,都是在全局作用域下實(shí)現(xiàn)的摔吏。無(wú)論是 setTimeout 還是 setInterval 里傳入的函數(shù),都會(huì)首先被交付到全局對(duì)象手上纵装。因此舔腾,函數(shù)中 this 的值,會(huì)被自動(dòng)指向 window搂擦。
嚴(yán)格模式下的this指向
- 普通函數(shù)中的 this 在嚴(yán)格模式下的表現(xiàn):
所謂 “普通函數(shù)” 稳诚,這里我們是相對(duì)于箭頭函數(shù)來(lái)說(shuō)的。在非嚴(yán)格模式下瀑踢,直接調(diào)用普通函數(shù)時(shí)扳还,函數(shù)中的 this 默認(rèn)指向全局變量(window 或 global)
function showThis() {
console.log(this)
}
showThis() // 輸出 Window 對(duì)象
而 在嚴(yán)格模式下,this 將保持它被指定的那個(gè)對(duì)象的值橱夭,所以氨距,如果沒(méi)有指定對(duì)象,this 就是 undefined :
'use strict'
function showThis() {
console.log(this)
}
showThis() // undefined
- 全局代碼中的 this 在嚴(yán)格模式下的表現(xiàn):
'use strict'
console.log(this) // 直接在全局代碼里嘗試去拿 this Window
'use strict'
var name = 'BigBear'
var me = {
name: 'xiuyan',
hello: function() {
// 全局作用域下實(shí)現(xiàn)的延時(shí)函數(shù)
setTimeout(function() {
console.log(`你好棘劣,我是${this.name}`)
})
}
}
me.hello() // 你好俏让,我是BigBear
像這樣 處于全局代碼中的 this, 不管它是否處于嚴(yán)格模式下,它的 this 都指向 Window(這點(diǎn)要特別注意首昔,容易誤以為這里也是 undefined )寡喝。
構(gòu)造函數(shù)中的this
當(dāng)我們使用構(gòu)造函數(shù)去 new 一個(gè)實(shí)例的時(shí)候:
function Person(name) {
this.name = name
console.log(this)
}
var person = new Person('xiuyan')
構(gòu)造函數(shù)里面的 this 會(huì)綁定到我們 new 出來(lái)的這個(gè)對(duì)象person
上。
Q2:使用new來(lái)調(diào)用函數(shù)勒奇,或者發(fā)生構(gòu)造函數(shù)調(diào)用時(shí)發(fā)生了什么预鬓?
- 創(chuàng)建一個(gè)全新的對(duì)象
- 這個(gè)新對(duì)象會(huì)執(zhí)行[[Prototype]]連接
- 這個(gè)新對(duì)象會(huì)綁定到函數(shù)調(diào)用的this
- 如果函數(shù)沒(méi)有返回其他對(duì)象,那么new表達(dá)式中的函數(shù)調(diào)用會(huì)自動(dòng)返回這個(gè)新對(duì)象
箭頭函數(shù)中this的指向
箭頭函數(shù)和閉包很相似赊颠,都是認(rèn)“死理”—— 認(rèn)“詞法作用域”的家伙格二。所以說(shuō) 箭頭函數(shù)中的 this,和你如何調(diào)用它無(wú)關(guān)竣蹦,由你書(shū)寫(xiě)它的位置決定(和普通函數(shù)的 this 規(guī)則恰恰相反~)
var name = 'BigBear'
var mefun = function(){
this.name = 'xiuyan';
return () => {
console.log(this.name)
};
}
var me = {
name: 'xiuyan',
// 聲明位置 此時(shí)作用域是全局作用域
hello: () => {
console.log(this.name)
}
}
// 調(diào)用位置
me.hello() // BigBear
mefun()(); // xiuyan
如何改變this的指向顶猜?
- 通過(guò)改變書(shū)寫(xiě)代碼的方式做到(比如箭頭函數(shù))
當(dāng)我們將普通函數(shù)改寫(xiě)為箭頭函數(shù)時(shí),箭頭函數(shù)的 this 會(huì)在書(shū)寫(xiě)階段(即聲明位置)就綁定到它父作用域的 this 上痘括。無(wú)論后續(xù)我們?nèi)绾握{(diào)用它长窄,都無(wú)法再為它指定目標(biāo)對(duì)象 —— 因?yàn)?箭頭函數(shù)的 this 指向是靜態(tài)的,“一次便是一生”远寸。 - 顯式地調(diào)用一些方法來(lái)幫忙抄淑,如
call
屠凶、apply
驰后、bind
- call、apply 和 bind 之間的區(qū)別比較大:
call
矗愧、apply
在改變 this 指向的同時(shí)灶芝,直接執(zhí)行目標(biāo)函數(shù);
bind
則只負(fù)責(zé)改造 this唉韭,不作任何執(zhí)行操作夜涕,返回一個(gè)綁定上下文的函數(shù)。 - call 和 apply 之間的區(qū)別属愤,則體現(xiàn)在對(duì)入?yún)⒌囊笊希?br>
call
只需要將目標(biāo)函數(shù)的入?yún)⒅饌€(gè)傳入即可女器;
apply
則希望入?yún)⒁詳?shù)組形式被傳入。
模擬實(shí)現(xiàn)call
方法 實(shí)現(xiàn)核心思想
- 改變 this 的指向住诸,將 this 綁到第一個(gè)入?yún)⒅付ǖ牡膶?duì)象上去驾胆;
- 根據(jù)輸入的參數(shù),執(zhí)行函數(shù)贱呐。
Function.prototype.myCall = function(context, ...args){
context.func = this;
context.func(...args);
delete context.func;
}
Function.prototype.myApply = function(context, arr){
context.func = this;
context.func(...arr);
delete context.func;
}
Function.prototype.myBind = function(context, ...args){
let self = this;
return function(){
self.call(context, ...args)
}
}
var name = 'global';
var me = {
name: 'hah'
}
function showName(){
console.log(this.name);
}
function showFullName(firstNama, lastName){
console.log(`${this.name} ${firstNama}_${lastName}`);
}
showName(); // global
showName.myCall(me); // hah
showFullName.myCall(me, 'Bubble', 'M'); // hah Bubble_M
showFullName.apply(me, ['Bubble', 'M']); // hah Bubble_M
showFullName.myApply(me, ['Bubble','M']); // hah Bubble_M
showFullName.bind(me, 'Bubble', 'M')(); // hah Bubble_M
showFullName.myBind(me, 'Bubble', 'M')(); // hah Bubble_M
擴(kuò)充思考:
Q:如果我們第一個(gè)參數(shù)傳了 null 怎么辦丧诺?是不是可以默認(rèn)給它指到 window 去?A:context = context || global;
Q:函數(shù)如果是有返回值的話怎么辦奄薇?是不是新開(kāi)一個(gè) result 變量存儲(chǔ)一下這個(gè)值驳阎,最后 return 出來(lái)就可以了?
Function.prototype.myCall = function(context, ...args){
context = context || window;
context.func = this;
let result = context.func(...args);
delete context.func;
return result;
}
其他
Reference 類型與 this 的指向密切關(guān)聯(lián)
ES3模擬實(shí)現(xiàn)apply和call