簡體   English   中英

javascript:如何解決匿名函數中的“不是函數”錯誤?

[英]javascript: how do I fix a 'not a function' error in an anonymous function?

我將一個簡單的javascript函數轉換為使用原型的函數。 現在,匿名函數中的調用將收到“不是函數”錯誤。

通過一些研究,我發現使用匿名函數時,“ this”的值可能並不總是您認為的。

那么,如何解決此問題?

這是顯示問題的簡化代碼。

 var chart; chart = function Chart(){ var xScale; } chart.prototype = { method1 : function() { this.xScale = d3.time.scale(); } method2 : function () { this.xScale(0); // No "not a function error here" // but I get the "not a function" error below when I call this.xScale(d.date) var overlay = d3.svg.area() .x(function (d) { return this.xScale(d.date); }) .y0(0) .y1(height); } } 

在調用d3.svg.area().x() this是最有可能的,指的是area對象。 如果要使用function(d){} ,則最簡單的方法是在此調用之外創建另一個引用當前對象的變量:

method2 : function () {
    this.xScale(0);  // No "not a function error here"

    // store the current this here
    var thisChart = this;

    var overlay = d3.svg.area()
      .x(function (d) { return thisChart.xScale(d.date); })
      .y0(0)
      .y1(height);
}

順便提一句,正如t.niese所建議的那樣,要確保已定義scaleX ,依靠method1method2之前開始調用不是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM