this 是 JavaScript 中容易混淆的概念。它通常指向目前函式被呼叫時的所屬物件,但實際指向會依呼叫方式而改變。
const name = 'global';
function introduce() {
console.log(this.name);
}
introduce();
const myObject = {
name: 'Rebecca',
sayHello: function () {
console.log(this.name);
}
};
myObject.sayHello();
const input = document.getElementById('name');
input.onclick = function () {
console.log(this.value);
};
此時 this 指向 input 元素本身。
const laruence = { name: 'laruence' };
function introduce() {
console.log(this.name);
}
introduce.call(laruence);
const hello = introduce.bind(laruence);
hello();
總結來說,判斷 this 指向時,重點是看函式是怎麼被呼叫的。誰呼叫函式,this 通常就指向誰。