知識社群登入
事件處理與 this 環境變數
by 蘇德宙, 2011-02-07 12:40, 人氣(1498)
隱含的環境參數 this
// method ,代表此 method 的物件
var rect  = {
        width: 10, height: 10,
        setSize: function(w, h) {
            this.width = w, this.height = h;
        }
}
rect.setSize(20, 20);
 
// 一般 function,全域物件
var a = 0;
function f()
{
    var a = 1;
    alert (this.a);  // 0
    alert(a);  // 1
}
 
//
<div id=foo>click me!</div>
<script>
  function obj(el) {
    this.id = 1;
    this.el = el;
    this.el.onclick = this.clickHandler;
  }  
  obj.prototype.handler = function(event) {
    alert(this.id);
  }
 
  var a = new obj(document.getElementById("foo"));
  a.handler();          // 隱性地傳入 a 物件當做 handler 中的 this

  a.handler.call(a.el); // call 的第一個參數傳入 a.el 當做 handler 中的 this
  // click div 時,browser 會將 dom 元素傳入當做 handler 中的 this
</script>