2010-11-18 182 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)); 
},