2010-07-23 66 views
0

我有我正在嘗試構建的以下類文件。我想通過eventListener將多個變量傳遞給該方法,但下面的代碼不起作用,可能是由於作用域。不知道我應該改變什麼。任何意見將不勝感激。通過addEventListener將類變量傳遞給原型中的類方法

var MyClass= new Class.create(); 
MyClass.prototype = { 
    initialize: function(id,name,top,left){ 
     try{ 
      this.id = id; 
      this.name = name; 
      this.currentTop = top; 
      this.currentLeft = left; 

      $(id).addEventListener("mousedown",function(event,this.id,this.name){ 
       this.grabOBJ(event,this.id,this.name); 
      },false); 

     } 
     catch(error){alert(error);} 
    }, 
    grabOBJ:function(event,myID,myName){ 
     // do something here with myID and myName 
    } 
}; 

回答

0

您的語法是完全錯誤的。

相反,你應該做一個獨立的變量來保存真實this,像這樣:

var MyClass= new Class.create(); 
MyClass.prototype = { 
    initialize: function(id,name,top,left){ 
     try{ 
      this.id = id; 
      this.name = name; 
      this.currentTop = top; 
      this.currentLeft = left; 

      var self = this; 

      $(id).addEventListener("mousedown",function(event){ 
       self.grabOBJ(event); 
      }, false); 

     } 
     catch(error){alert(error);} 
    }, 
    grabOBJ:function(event){ 
     // do something here with this.id and this.name 
    } 
}; 

由於self.grabOBJ是正常的方法調用,其this將是MyClass實例。

+0

啊,是的。我現在明白了。我不能相信我錯過了這一點。感謝指針SLaks! – 2010-07-23 18:50:41