0

I have a object that I create two instances of:

    var generalGraph = new graph(generalFunnel)
    generalGraph.draw("#conversion");

    var invoicingGraph = new graph(invoicingFunnel)
    invoicingGraph.draw("#invoicing")

Here is the object (note that this is highly simplified to make it easier to understand) the comments are the console-outputs.

graph = function(funnel){
    this.funnel = funnel.conversions
    mySelf = this

    this.draw = function(selector){
        console.log(mySelf.funnel)
        //generalGraph ["Användare", "Påbörjat Onboarding", "Skapat oganisation", "Skapat användare", "Kom tillbaka", "Köpt"]
        //invoicingGraph ["Användare", "Påbörjat Onboarding", "Skapat oganisation", "Kom tillbaka", "Köpt"]
        nv.addGraph(function() {

            console.log(mySelf.funnel)
            //generalGraph ["Användare", "Påbörjat Onboarding", "Skapat oganisation", "Kom tillbaka", "Köpt"]
            //invoicingGraph ["Användare", "Påbörjat Onboarding", "Skapat oganisation", "Kom tillbaka", "Köpt"]
        });
    }

}

For some reason, when I do generalGraph.draw, it uses the funnel from invoicingFunnel. Why? And how can I stop it from happening?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Himmators
  • 14,278
  • 36
  • 132
  • 223
  • I don't know, the reason i do mySelf = this is that, this is sometimes changed, for example inside nv.addGraph. – Himmators Dec 16 '14 at 16:27

1 Answers1

4

mySelf is a global variable, you're missing a var before it. For this reason both of your graph instances use the same mySelf value.

Change:

mySelf = this

To

var mySelf = this
  • See this question on the differences between using and ommitting var.

  • You can prevent these errors in the future by using strict mode which will spot these errors for you.

  • Omitting semicolons in JavaScript is possible but is considered very risky because of the complicated rules it involves. It is generally frowned upon to do it today.
  • Similarly - constructor names in JS typically start with a capital letter. Your constructor should probably be defined with the var keyword as well.
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504