2010-11-18 135 views
2

我在javascript中进行范围设定时遇到了一些麻烦。我正在使用jquery插件编写一个类,它是我们的下拉控件的包装。Javascript范围问题

问题出在loadJsonList函数中,this.addOption(s.itemValue, s.itemText);的调用不起作用,因为该方法不存在。我知道JS有奇怪的范围,但我不知道如何在该范围内运行该功能?

jQuery.Class.extend("DDL", 
{ 
    id: '', 
    isTelerik: false 
}, 
{ 
    init: function (newid) { 
     this.Class.id = newid; 

    }, 
    getValue: function() { 
     return $('#' + this.Class.id).val(); 
    }, 
    getText: function() { 
     return $('#' + this.Class.id + ' :selected').text(); 
    }, 
    setValue: function (newValue) { 
     try { 
      $('#' + this.Class.id).val(newValue); 
     } catch (err) { 
      alert(err); 
     } 
    }, 
    setText: function (newText) { 
     try { 
      $('#' + this.Class.id + ' :selected').text(newText); 
     } catch (err) { 
      alert(err); 
     } 
    }, 
    loadJsonList: function (list, param1, param2, param3) { 
     this.clearItems(); 

     //init the service 
     var j = new JsonRPC(); 

     // get the cut down data table 
     var dt = j.getDropDownData(list, param1, param2, param3); 

     // parse the datatable and load it into the telerik combo box 
     jQuery.each(dt, function (i, s) { 
      this.addOption(s.itemValue, s.itemText); 
     }); 
    }, 
    addOption: function (value, text) { 
     $('#' + this.Class.id).append('<option value="' + value + '">' + text + '</option>'); 
    }, 
    removeOption: function (value) { 
     $('#' + this.Class.id + ' option[value="' + value + '"]').remove(); 
    }, 
    clearItems: function() { 
     $('#' + this.Class.id + ' option').remove(); 
    } 
}); 
+1

稍微迂腐,谈论'this'你不是在谈论范围界定,但结合时。 – slebetman 2010-11-18 03:03:05

回答

3

简单的一个。 JavaScript使用功能级别的作用域,所以你节省下一些其他的名字到this变量的引用:

loadJsonList: function (list, param1, param2, param3) { 
     // save a reference for use in the each function later 
     var self = this; 
     this.clearItems(); 

     //init the service 
     var j = new JsonRPC(); 

     // get the cut down data table 
     var dt = j.getDropDownData(list, param1, param2, param3); 

     // parse the datatable and load it into the telerik combo box 
     jQuery.each(dt, function (i, s) { 
      // use self instead of this! 
      self.addOption(s.itemValue, s.itemText); 
     }); 
    }, 
2

this在该函数的范围不等于你的对象的同一this,你需要指定一个别名变量它在以访问它的内部函数内周边范围:

var self = this;  
jQuery.each(dt, function (i, s) { 
    self.addOption(s.itemValue, s.itemText); 
}); 
0

你所寻找的是jQuery的代理方法(http://api.jquery.com/jQuery.proxy):

// Description: Takes a function and returns a new one that will always have a particular context. 
jQuery.proxy(function, context) 

因此,在你上面的例子如下你使用它:

loadJsonList: function (list, param1, param2, param3) { 

    // ... 

    jQuery.each(dt, jQuery.proxy(function (i, s) { 
     this.addOption(s.itemValue, s.itemText); 
    }, this)); 
},