繁体   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