DIV CSS 佈局教程網

JavaScript 的 this 與變數作用域:跨瀏覽器行為實測整理
編輯:關於JavaScript     

先釐清一個常見誤會:這裡談的 prototype 是 JavaScript 語言本身的特性,不是那個知名的 Prototype 框架。

0. 關於 prototype

用它可以替內建型別擴充方法:

<script type="text/javascript">
var string = "hello world";
try {
  alert(string.phone());
} catch(e) { alert(e); }

String.prototype.phone = function() {
  return "159-10957151";
}

alert(string.phone());
</script>

第一次呼叫會因為方法還不存在而丟出錯誤,被 catch 攔下;擴充之後第二次就能正常取得結果。

1. 物件方法中的 this

var deep_thought = {
  the_answer: 42,
  ask_question: function () {
    return this.the_answer;
  }
};

var the_meaning = deep_thought.ask_question();
alert(the_meaning);   // 42

因為函式是「以方法的身分」被呼叫,this 指向的就是 deep_thought 這個物件。

2. 直接呼叫函式時,this 是誰

function test_this() {
  return this;
}
var i_wonder_what_this_is = test_this();
alert(i_wonder_what_this_is);   // [object window]

在非嚴格模式下,直接呼叫的函式,this 會被指定為全域物件,也就是 window。

3. 行內事件中的 this

function click_handler() {
  alert(this);   // 彈出 window 物件
}
<button id='thebutton' onclick='click_handler()'>Click me!</button>

注意這裡彈出的是 window,不是那顆按鈕。原因很單純:你呼叫的是一個「函式」,而不是把函式掛成元素的方法。

4. 把元素明確傳進去

function click_handler(obj) {
  alert(obj);   // [object HTMLButtonElement]
}
<button id='thebutton' onclick='click_handler(this)'>Click me!</button>

在行內屬性裡,this 指的是元素本身,因此這樣寫就能正確拿到按鈕。這也是為什麼行內寫法反而比較不容易出錯。

5. 把方法指派給元素,this 就飄走了

function BigComputer(answer) {
  this.the_answer = answer;
  this.ask_question = function () {
    alert(this.the_answer);
  }
}

function addhandler() {
  var deep_thought = new BigComputer(42),
      the_button = document.getElementById('thebutton');
  the_button.onclick = deep_thought.ask_question;
}
window.onload = addhandler;
// 結果:undefined

這是最經典的坑。方法一旦被指派成元素的事件處理器,呼叫時的 this 就會變成那個元素,而不是原本的 deep_thought,所以 this.the_answer 自然是 undefined。

6. 用 self 保留參考

解法是在建構函式中先把 this 存進一個區域變數,再透過它來存取:

function BigComputer(answer) {
  var self = this;
  self.the_answer = answer;
  self.ask_question = function () {
    alert(self.the_answer);
  }
}

由於 self 被閉包保留下來,無論這個函式被誰呼叫,都能正確指向原本的物件。

補充:現代寫法

今天若不需要支援舊版瀏覽器,同樣的需求用箭頭函式或 bind() 都能更簡潔地解決:the_button.onclick = deep_thought.ask_question.bind(deep_thought)。但理解 this 的綁定規則永遠是前提——工具變了,規則沒變。

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