DIV CSS 佈局教程網

JavaScript this 指向解析:函數、物件與事件
編輯:JavaScript基礎知識     

this 是 JavaScript 中容易混淆的概念。它通常指向目前函式被呼叫時的所屬物件,但實際指向會依呼叫方式而改變。

基本原則

  • 若函式作為物件方法呼叫,this 指向該物件。
  • 若只是普通函式呼叫,this 通常指向全域物件。
  • 若使用 call、apply 或 bind,this 會依指定物件決定。
  • 若在事件處理中,this 通常指向觸發事件的元素。

普通函式

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 元素本身。

call、apply 與 bind

const laruence = { name: 'laruence' };

function introduce() {
  console.log(this.name);
}

introduce.call(laruence);

const hello = introduce.bind(laruence);
hello();

總結來說,判斷 this 指向時,重點是看函式是怎麼被呼叫的。誰呼叫函式,this 通常就指向誰。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved