在 Java 等面向?qū)ο蟮恼Z言中,this 關(guān)鍵字的含義是明確且具體的,即指代當(dāng)前對象。一般在編譯期綁定。而 在 JavaScript 中,this 是動(dòng)態(tài)綁定,或稱為運(yùn)行期綁定的 ,由于其運(yùn)行期綁定的特性,JavaScript 中的 this 含義要豐富得多,它可以是全局對象、當(dāng)前對象或者任意對象,這完全取決于函數(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
上面這段代碼可以在不同的上下文對象(me和you)中重復(fù)使用函數(shù)identify和speak,不用針對每個(gè)對象編寫不同版本的函數(shù)。
如果不使用this,那就需要給identify和speak顯式傳入一個(gè)上下文對象:
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)雅的方式來隱式“傳遞”一個(gè)對象引用,因此可以將API設(shè)計(jì)得更加簡潔并易于復(fù)用。
this指向誰?
多數(shù)情況下,this 指向調(diào)用它所在方法的那個(gè)對象。當(dāng)調(diào)用方法沒有明確對象時(shí),this 就指向全局對象。在瀏覽器中,指向 window;在 Node 中,指向 Global。(嚴(yán)格模式下,指向 undefined)
?? this 的指向是在調(diào)用時(shí)決定的,而不是在書寫時(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?的確,我們打眼看過去,直覺上肯定會(huì)認(rèn)為是 you 這個(gè)對象在調(diào)用 hello 方法、進(jìn)而調(diào)用 targetFunc,所以此時(shí) this 肯定指向 you 對象??!為啥會(huì)輸出一個(gè) window 上的 name 呢?
“this 指向調(diào)用它所在方法的那個(gè)對象”
回頭看 targetFunc 這個(gè)方法,之所以第一直覺會(huì)認(rèn)為它的 this 應(yīng)該指向 you 這個(gè)對象,其實(shí)還是因?yàn)榘?“聲明位置” 和 “調(diào)用位置” 混淆了。我們看到雖然 targetFunc 是在 you 對象的 hello 方法里聲明的,但是在調(diào)用它的時(shí)候,我們是不是沒有給 targetFunc 指明任何一個(gè)對象作為它前綴? 所以 you 對象的 this 并不會(huì)神奇地自動(dòng)傳入 targetFunc 里,js 引擎仍然會(huì)認(rèn)為 targetFunc 是一個(gè)掛載在 window 上的方法,進(jìn)而把 this 指向 window 對象。
一定要記住“不管方法被書寫在哪個(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ì)(也無法)通過屬性訪問器( 即 xx.xxx) 這樣的形式來給它指定一個(gè)所在對象,所以它的 this 是非常確定的,就是默認(rèn)的全局對象 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)的。無論是 setTimeout 還是 setInterval 里傳入的函數(shù),都會(huì)首先被交付到全局對象手上。因此,函數(shù)中 this 的值,會(huì)被自動(dòng)指向 window。
嚴(yán)格模式下的this指向
- 普通函數(shù)中的 this 在嚴(yán)格模式下的表現(xiàn):
所謂 “普通函數(shù)” ,這里我們是相對于箭頭函數(shù)來說的。在非嚴(yán)格模式下,直接調(diào)用普通函數(shù)時(shí),函數(shù)中的 this 默認(rèn)指向全局變量(window 或 global)
function showThis() {
console.log(this)
}
showThis() // 輸出 Window 對象
而 在嚴(yán)格模式下,this 將保持它被指定的那個(gè)對象的值,所以,如果沒有指定對象,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 出來的這個(gè)對象person上。
Q2:使用new來調(diào)用函數(shù),或者發(fā)生構(gòu)造函數(shù)調(diào)用時(shí)發(fā)生了什么?
- 創(chuàng)建一個(gè)全新的對象
- 這個(gè)新對象會(huì)執(zhí)行[[Prototype]]連接
- 這個(gè)新對象會(huì)綁定到函數(shù)調(diào)用的this
- 如果函數(shù)沒有返回其他對象,那么new表達(dá)式中的函數(shù)調(diào)用會(huì)自動(dòng)返回這個(gè)新對象
箭頭函數(shù)中this的指向
箭頭函數(shù)和閉包很相似,都是認(rèn)“死理”—— 認(rèn)“詞法作用域”的家伙。所以說 箭頭函數(shù)中的 this,和你如何調(diào)用它無關(guān),由你書寫它的位置決定(和普通函數(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的指向?
- 通過改變書寫代碼的方式做到(比如箭頭函數(shù))
當(dāng)我們將普通函數(shù)改寫為箭頭函數(shù)時(shí),箭頭函數(shù)的 this 會(huì)在書寫階段(即聲明位置)就綁定到它父作用域的 this 上。無論后續(xù)我們?nèi)绾握{(diào)用它,都無法再為它指定目標(biāo)對象 —— 因?yàn)?箭頭函數(shù)的 this 指向是靜態(tài)的,“一次便是一生”。 - 顯式地調(diào)用一些方法來幫忙,如
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)在對入?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)⒅付ǖ牡膶ο笊先ィ?/li>
- 根據(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ù)如果是有返回值的話怎么辦?是不是新開一個(gè) result 變量存儲一下這個(gè)值,最后 return 出來就可以了?
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