0

我在 javascript 中创建了一个名为 QuoteProductService() 的“类”,见下文。我在原型中添加了两个函数,现在,我试图从另一个函数 (getFakeQuoteProducts) 内的 jquery $.each 中调用其中一个函数 (getQuoteProductFromArray)。这行不通。我尝试添加“this.”,但这也不起作用,因为 .each 中的“this”指的是循环中的当前元素。

我该怎么做?

function QuoteProductService() {

}

QuoteProductService.prototype.getQuoteProductFromArray =  function(quoteproductarray, quoteproductid){
     var founditem=null;
     // do stuff
    return founditem;
}

QuoteProductService.prototype.getFakeQuoteProducts = function(){
    // do something to fill the mappedQuoteProducts array
    $.each(mappedQuoteProducts, function (index, quoteproduct) {
        if (quoteproduct!=-null) {
            if (quoteproduct.parentid != "") {
                // this is where it goes wrong :
                var parent = getQuoteProductFromArray(mappedQuoteProducts, quoteproduct.parentid);
                if (parent != null) {
                    parent.attachChild(quoteproduct);
                }
            }
        }
    });
}
4

3 回答 3

4

在调用之前保存对您的QuoteProductService实例的引用each

QuoteProductService.prototype.getFakeQuoteProducts = function(){
  var _this = this;
  // do something to fill the mappedQuoteProducts array
  $.each(mappedQuoteProducts, function (index, quoteproduct) {
      if (quoteproduct!=-null) {
          if (quoteproduct.parentid != "") {
              // this is where it goes wrong :
              var parent = _this.getQuoteProductFromFlatArray(mappedQuoteProducts, quoteproduct.parentid);
              if (parent != null) {
                  parent.attachChild(quoteproduct);
              }
          }
       }
    });
}
于 2012-11-19T12:07:30.293 回答
1

添加var self = this;getFakeQuoteProducts函数的开头。然后getQuoteProductFromFlatArray像这样调用:self.getQuoteProductFromFlatArray.

于 2012-11-19T12:07:37.913 回答
1

首先,您提供了错误的方法名称 -getQuoteProductFromFlatArray而不是getQuoteProductFromArray. 其次,在 JS 中,您必须为实例方法提供范围。实现这一点的最简单方法是将this引用存储到其他一些私有变量中。请参见下面的示例。

function QuoteProductService() {

}

QuoteProductService.prototype.getQuoteProductFromArray =  function(quoteproductarray, quoteproductid){
     var founditem=null;
     // do stuff
    return founditem;
}

QuoteProductService.prototype.getFakeQuoteProducts = function(){
    var me = this; // store this into me

    // do something to fill the mappedQuoteProducts array
    $.each(mappedQuoteProducts, function (index, quoteproduct) {
        // this === me will return false
        if (quoteproduct!=-null) {
            if (quoteproduct.parentid != "") {
                // this is where it goes wrong :
                var parent = me.getQuoteProductFromArray(mappedQuoteProducts, quoteproduct.parentid);
                if (parent != null) {
                    parent.attachChild(quoteproduct);
                }
            }
        }
    });
}
于 2012-11-19T12:08:55.453 回答