admin管理员组

文章数量:1225001

I am trying to use d3.js to draw line chart.

Javascript

function lineChart(){
    ...
}

function update(){
    ...
    var lineChart = lineChart()
        .x(d3.scale.linear().domain([2011, 2014]))
        .y(d3.scale.linear().domain([0, 1000000]));
    ...
}

But the console says that Uncaught TypeError: lineChart is not a function.
How to fix this?

I am trying to use d3.js to draw line chart.

Javascript

function lineChart(){
    ...
}

function update(){
    ...
    var lineChart = lineChart()
        .x(d3.scale.linear().domain([2011, 2014]))
        .y(d3.scale.linear().domain([0, 1000000]));
    ...
}

But the console says that Uncaught TypeError: lineChart is not a function.
How to fix this?

Share Improve this question asked Apr 26, 2016 at 8:44 MironMiron 1,0672 gold badges19 silver badges32 bronze badges 3
  • 5 use var lineChartResult = lineChart()... – Andreas Louv Commented Apr 26, 2016 at 8:45
  • 1 Just change variable name. thats it – Dilip Oganiya Commented Apr 26, 2016 at 8:49
  • Does this answer your question? JavaScript error: "is not a function" – Liam Commented Apr 5, 2022 at 13:34
Add a comment  | 

3 Answers 3

Reset to default 7

You are shadowing your function.

This happens when you declare another variable/function with the same name of an upper one. What you should do is to give another name to the second one declaration just like @andlrc says in his comment.

var lineChartResult = lineChart()...

You can learn more about shadowing in here: Setting & Shadowing Properties

If you declare a variable with the name of an existing function, that function is no longer available within that context (is shadowed by the variable). Change the name of the variable to avoid that naming collision.

This code is equivalente to yours, maybe you can see what is happening:

function lineChart() {...} //function declared

function update() {
    var lineChart; // variable created, its value is undefined
    lineChart=lineChart() // linechart is not a function, is an undefined value!
}

Another solution, if you don't want to change your variable name, is to qualify the method name with this to disambiguate it from the variable name that precedes it:

var lineChart = this.lineChart()...

本文标签: jqueryUncaught TypeErroris not a function in javascriptStack Overflow