[英]javascript: how do I fix a 'not a function' error in an anonymous function?
I converted a simple javascript function into one that uses a prototype. 我将一个简单的javascript函数转换为使用原型的函数。 Now a call in an anonymous function is getting the "not a function" error.
现在,匿名函数中的调用将收到“不是函数”错误。
From some researching, I see the value of 'this' may not always be what you think it is when an anonymous function is used. 通过一些研究,我发现使用匿名函数时,“ this”的值可能并不总是您认为的。
So, how do I fix this problem? 那么,如何解决此问题?
Here's the cut-down code to show the problem. 这是显示问题的简化代码。
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); } }
Within the call to d3.svg.area().x()
, this
is, most likely, referring to the area
object. 在调用
d3.svg.area().x()
this
是最有可能的,指的是area
对象。 If you want to use your function(d){}
, it is easiest to just create another variable referring to your current object outside of this call: 如果要使用
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);
}
By the way, as t.niese suggests, it's not a good idea to rely on method1
begin called before method2
, to ensure that scaleX
is defined. 顺便提一句,正如t.niese所建议的那样,要确保已定义
scaleX
,依靠method1
在method2
之前开始调用不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.