内部函数无法访问外部函数的范围,因此无法读取属性toString()的未定义错误

时间:2014-05-30 13:42:29

标签: javascript scope closures

我无法从内部函数访问外部函数中条件块中实例化的this.curr_prod_data数组。我正在将一个标志变量传递给外部函数来测试对象是否已经实例化。

如果它已经实例化(flag = 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);
        }
    }
 } 

1 个答案:

答案 0 :(得分:0)

我将curr_prod_data数组作为函数的静态对象。知道为什么我必须这样做才能使这个工作吗?

    addProdData.curr_prod_data =[];

    function addProdData(p_id, tick_sym , ind, curr_price, _flag) {
       this.a;
       this.flag = _flag;


      if(!this.flag) {
        addProdData.curr_prod_data[ind] = new ProductMarketData(p_id, tick_sym, ind, null, null, null);
        console.log("object: "+addProdData.curr_prod_data[ind].toString());
        addProdData.curr_prod_data[ind].updateCurrentQuote(curr_price);
        this.a ="hi";
      } else {
          updateold(ind, curr_price);
      }

   function updateold(price, index) {
       console.log("ind "+index);
       console.log("a "+this.a);
       addProdData.curr_prod_data[index].updateCurrentQuote(price);
   }
}