【发布时间】:2014-05-30 13:42:28
【问题描述】:
我无法从内部函数访问在外部函数的条件块中实例化的this.curr_prod_data 数组。我将一个标志变量传递给外部函数以测试对象是否已经实例化。
如果它已经被实例化(标志=1),我只想在已经创建的对象上调用方法updateCurrentQuote。为了测试范围,我创建了一个测试变量“a”,我在if 块中分配了它。我可以在内部函数中访问它。这是我的代码:
function addProdData(p_id, tick_sym , ind, curr_price, length, _flag) {
this.a;
this.flag = _flag;
this.curr_prod_data = new Array(length);
if(!this.flag) {
this.curr_prod_data[ind] = new ProductMarketData(p_id, tick_sym, ind, null, null, null);
console.log("object: "+ this.curr_prod_data[ind].toString()); //Prints properties of class object
this.curr_prod_data[ind].updateCurrentQuote(curr_price); //No error
this.a = "hi";
}
else {
updateold(curr_price, ind);
}
function updateold(price, index) {
console.log("ind "+index);
console.log("a "+this.a); //Prints value of a: Hi
console.log("object: "+ this.curr_prod_data[index].toString()); //Gives cannot read property toString of undefined
this.curr_prod_data[index].updateCurrentQuote(price);
}
}
这是我调用函数的地方
if(js_object[0].hasOwnProperty('tickerSymbol')) {
for(var j = 0; j < size; ++j) {
var flag = 0;
if($("#product_select li").length > 0) {
$("#product_select li a").each(function() {
if(($.trim($(this).html())) == js_object[j].tickerSymbol){
flag = 1;
}
});
}
console.log("flag: "+ flag);
if(!flag) {
$("#product_select").append("<li id ="+j+"><a>" + js_object[j].tickerSymbol + "</a></li>");
$("#product_select li:eq(0) a").css({"background-color": "lightblue", "border-color" : "blue"});
addProdData(js_object[j].productID, js_object[j].tickerSymbol, j, js_object[j].curr_price, size, flag);
}
else {
console.log("oldj ="+ j);
addProdData(js_object[j].productID, js_object[j].tickerSymbol, j, js_object[j].curr_price, size, flag);
}
}
}
【问题讨论】:
-
你是如何调用
addProdData的?它是对象上的方法,还是事件侦听器,还是简单地用addProdData(...)调用? -
使用参数简单调用
-
是的,你是对的,当我将声明更改为 this.curr_prod_data = new Array(length);它让我无法在内部函数“updateold”中的未定义上调用方法 toString()
-
请编辑您的问题并向我们展示更多代码。
-
我添加了更多代码
标签: javascript scope closures