DIV CSS 佈局教程網

JavaScript 中 this 的工作原理與範例詳解
編輯:JavaScript綜合知識     

this 是 JavaScript 中最容易令人困惑的機制之一。本文透過一系列範例,說明 this 在不同情境下的指派規則,以及如何用 call、apply、bind 操控它。

this 的基本指派

當函式作為某物件的方法被呼叫時,this 會指向該物件:

var parent = {
  method: function () {
    console.log(this);
  }
};
parent.method(); // <- parent

但這種行為很「脆弱」:若取得方法的參考後再呼叫,this 就會變成 window 全域物件,這點常令開發者困惑。

用 call、apply、bind 改變 this

Function.prototype.call 的第一個參數指派給 this,其餘參數則傳入函式:

Array.prototype.slice.call([1, 2, 3], 1, 2) // <- [2]

apply 與 call 類似,但它傳入的是一個陣列:

String.prototype.split.apply('13.12.02', ['.']) // <- ['13', '12', '02']

bind 則會建立一個永遠使用指定 this 的新函式,還能預先綁定部分參數:

var arr = [1, 2];
var add = Array.prototype.push.bind(arr, 3);
add();    // effectively the same as arr.push(3)
add(4);   // effectively the same as arr.push(3, 4)
console.log(arr); // <- [1, 2, 3, 3, 4]

作用域鏈中的 this

在巢狀函式中,this 無法沿著作用域鏈保持不變,這是規則的缺陷:

function scoping () {
  console.log(this);
  return function () {
    console.log(this);
  };
}
scoping()(); // <- Window // <- Window

常見解法是建立一個區域變數保存 this 的參考:

function retaining () {
  var self = this;
  return function () {
    console.log(self);
  };
}
retaining()(); // <- Window

或者更優雅地使用 bind 將父作用域的 this 指定給子作用域:

function bound () {
  return function () {
    console.log(this);
  }.bind(this);
}
bound()(); // <- Window

理解這些規則後,就能準確預測並控制 this 的指向,避免常見的作用域陷阱。

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