访问父javascript对象的变量和方法?

时间:2009-09-24 13:03:47

标签: javascript mootools

var SortingTable = new Class({
          initialize: function( table, options ) {
               this.table=$(table);
               this.tbody = this.table.getElement('tbody');
               //...do alot of things here... 
        },
          addTextInput : function(index,headid,options){
            var trs = this.tbody.getChildren();
            var trslen = trs.length;
            var i=0;
            var cell = null;
            for(i=0;i<trslen;i++){
                cell = trs[i].getChildren()[index];
                cell.addEvent('dblclick', function (event){
                      alert(this.innerHTML); // i can see this is the cell here. 
                      this.makeCellEditor(this); // how to access the parent object? 
                });
            }
          },
           makeCellEditor : function(cell){
              //make form and stuff here.   
          }
    //...alot of more functions... 
});

在我的dblclick(事件)函数中,我想访问我在“父”对象中声明的函数makeCellEditor。

3 个答案:

答案 0 :(得分:3)

   var self = this;
   cell.addEvent('dblclick', function (event){
                  alert(this.innerHTML); // i can see this is the cell here. 
                  self.makeCellEditor(this);
            });

答案 1 :(得分:1)

您可以将this引用保存在另一个变量中,以使其可供事件处理程序访问,如下所示:

addTextInput: function(...) {
  var self = this;

  ...

  cell.addEvent('dblclick', function(event) {
    self.makeCellEditor(this);
  });
}

在事件处理程序中,this引用单元格,并且self可通过闭包作为外部this对象SortingTable的引用。

答案 2 :(得分:0)

你也可以通过附加.bind(this)绑定匿名函数;并将'this'的范围更改为类,单元格已包含对您可以使用的单击对象的引用...

for(i=0;i<trslen;i++){
    cell = trs[i].getChildren()[index];
    cell.addEvent('dblclick', function (event){
          alert(cell.get("html")); 
          this.makeCellEditor(cell); 
    }.bind(this));
}

我倾向于支持这种解决方案,因为它不涉及对整个类(self = this)进行新的引用,即使它是局部范围,但有时它是不可避免的。

您还可以阅读此http://mootools.net/docs/core/Native/Function#Function:bindWithEvent

相关问题