我在 javascript 中创建了一个名为 QuoteProductService() 的“类”,请参见下文。 我已经向原型(prototype)添加了两个函数,现在,我尝试从另一个函数 (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);
}
}
}
});
}
最佳答案
在调用 each
之前保存对 QuoteProductService
实例的引用
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);
}
}
}
});
}
关于javascript - 从 jquery 的 .each 内部调用父级的父级中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13453437/