DIV CSS 佈局教程網

徹底搞懂 JavaScript 關鍵字 this 的指向規則
編輯:關於JavaScript     

本文整理自 Cody Lindley 的《JavaScript Enlightenment》,聚焦那個讓無數開發者頭疼的關鍵字 this,以及確定與設置 this 值的種種方法。

概念性理解 this

當一個函數被創建後,關鍵字 this 便隨之(在後台)產生,它鏈接到一個對象,而函數正是在這個對象上進行操作。換句話說,this 是對「包含該函數的對象」的引用。

var cody = {
  living: true,
  age: 23,
  gender: 'male',
  getGender: function(){ return this.gender; }
};
console.log(cody.getGender()); // 'male'

這裡 this 指向 cody 對象,因此 this.gender 等價於 cody.gender。一句話記住:this 通常指向包含函數的對象,而非函數本身(new、call()、apply() 等情況除外)。

如何確定 this 的值

this 會傳給所有函數,其值取決於函數「被調用時」的上下文。看下面的例子:

var foo = 'foo';
var myObject = { foo: 'I am myObject.foo' };
var sayFoo = function() { console.log(this['foo']); };

myObject.sayFoo = sayFoo;
myObject.sayFoo(); // 'I am myObject.foo'
sayFoo();          // 'foo'

myObject.sayFoo 與 sayFoo 指向同一函數,但調用上下文不同,this 的值也就不同——前者指向 myObject,後者指向全局對象。

嵌套函數中的 this 陷阱

在嵌套於另一函數內部的函數中,ECMAScript 3 下的 this 並不指向外層所屬的對象,而是指向全局對象(瀏覽器中的 window):

var foo = {
  func1: function(bar){
    bar(); // 記錄 window,而非 foo
    console.log(this); // 這裡的 this 指向 foo
  }
};
foo.func1(function(){ console.log(this) });

此問題在 ECMAScript 5 中通過嚴格模式得到修正。

解決方案:that 保存上下文

為避免 this 丟失,可在父函數中用一個變量(慣例命名為 that)保存對 this 的引用:

var myObject = {
  myProperty: 'I can see the light',
  myMethod: function() {
    var that = this;
    var helperFunction = function() {
      console.log(that.myProperty); // 'I can see the light'
    }();
  }
};
myObject.myMethod();

控制 this 的值:call 與 apply

可用 call() 或 apply() 顯式指定函數調用時 this 指向的對象:

var myObject = {};
var myFunction = function(param1, param2){
  this.foo = param1;
  this.bar = param2;
};
myFunction.call(myObject, 'foo', 'bar');  // 參數以逗號分隔
myFunction.apply(myObject, ['foo', 'bar']); // 參數以數組傳遞
console.log(myObject); // { foo: 'foo', bar: 'bar' }

構造函數與原型中的 this

當函數用 new 觸發時,this 指向新創建的實例:

var Person = function(name){
  this.name = name || 'johndoe';
};
var cody = new Person('Cody Lindley');
console.log(cody.name); // 'Cody Lindley'

若省略 new,this 將指向調用上下文(此時為全局對象),name 會被掛到 window 上,這是需要警惕的常見錯誤。

當方法掛在 prototype 上時,其中的 this 指向觸發該方法的實例;若實例本身沒有某屬性,查找會沿原型鏈向上進行:

Person.prototype.whatIsMyFullName = function(){
  return this.fullName;
};
console.log(new Person('cody lindley').whatIsMyFullName());

小結

掌握 this 的關鍵,是牢記它的值由「函數如何被調用」決定,而非「在哪裡定義」。理清普通調用、方法調用、new、call/apply 這幾種語境下的指向規則,就能擺脫 this 帶來的絕大多數困惑。

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