this 是 JavaScript 中最容易讓人困惑的概念之一。它的指向取決于函數(shù)的調(diào)用方式而非定義位置,且在不同場景下表現(xiàn)不同。
?
一、this 的本質(zhì)
this 是一個動態(tài)綁定的執(zhí)行上下文對象,指向當前函數(shù)運行時的“所有者”。它的值在函數(shù)被調(diào)用時確定,而非定義時。理解 this 的關鍵在于分析函數(shù)是如何被調(diào)用的。
二、綁定規(guī)則
1. 默認綁定(獨立函數(shù)調(diào)用)
當函數(shù)作為獨立函數(shù)調(diào)用時(非方法、構造函數(shù)等),非嚴格模式下 this 指向全局對象(瀏覽器中為 window),嚴格模式下為 undefined。
function showThis() {
console.log(this);
}
showThis();
2. 隱式綁定(方法調(diào)用)
當函數(shù)作為對象方法調(diào)用時,this 指向調(diào)用該方法的對象。
const obj = {
name: 'Object',
logThis() {
console.log(this.name);
}
};
obj.logThis();
?? 隱式丟失陷阱:方法被賦值給變量后調(diào)用會導致 this 丟失。const temp = obj.logThis;
temp();
3. 顯式綁定(call/apply/bind)
通過 call()
, apply()
或 bind()
強制指定 this 值。
function greet() {
console.log(`Hello, ${this.name}`);
}
const user = { name: 'Alice' };
greet.call(user);
const boundGreet = greet.bind(user);
boundGreet();
4. new 綁定(構造函數(shù))
使用 new 調(diào)用構造函數(shù)時,this 指向新創(chuàng)建的實例對象。
function Person(name) {
this.name = name;
}
const bob = new Person('Bob');
console.log(bob.name);
5. 箭頭函數(shù)
箭頭函數(shù)沒有自己的 this,繼承外層作用域的 this 值,且無法通過 call/apply 修改。
const obj = {
traditional: function() {
console.log(this);
},
arrow: () => {
console.log(this);
}
};
obj.traditional();
obj.arrow();
三、優(yōu)先級規(guī)則
當多個規(guī)則同時適用時,按以下優(yōu)先級決定 this 指向:
new 綁定 > 顯式綁定 > 隱式綁定 > 默認綁定
四、this的3個特殊使用場景
1. 回調(diào)函數(shù)中的 this
常見于定時器、事件監(jiān)聽等場景,需要特別注意 this 指向:
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this);
});
button.addEventListener('click', () => {
console.log(this);
});
2. 嵌套函數(shù)中的 this
內(nèi)部函數(shù)不會繼承外部函數(shù)的 this(除非使用箭頭函數(shù))
const obj = {
name: 'Obj',
outer() {
function inner() {
console.log(this);
}
inner();
}
};
3. 類中的 this
類方法中的 this 指向?qū)嵗龑ο螅枳⒁夥椒ㄗ鳛榛卣{(diào)時的綁定問題:
class Counter {
constructor() {
this.count = 0;
this.increment = this.increment.bind(this);
}
increment() {
this.count++;
}
}
五.this的4個實用小技巧
1.明確綁定:在需要固定 this 指向時,優(yōu)先使用箭頭函數(shù)或 bind
2.避免混用:同一函數(shù)中不要同時使用普通函數(shù)和箭頭函數(shù)定義方法
3.嚴格模式:使用 'use strict'
避免意外指向全局對象
4.調(diào)試技巧:在復雜場景中使用 console.log(this)
快速定位當前值
六、總結(jié)
| | |
---|
| | func() |
| | obj.method() |
| | new Constructor() |
| | func.call(ctx) |
| | () => {...} |
理解 this 的關鍵在于分析函數(shù)的調(diào)用位置和調(diào)用方式。通過掌握綁定規(guī)則和優(yōu)先級,可以準確預測代碼行為,避免常見陷阱。
閱讀原文:原文鏈接
該文章在 2025/3/27 13:25:03 編輯過