1

All of my elements which init by my jquery plugin sharing the same local variable when it running. I did a test and found out because this line:

var tmp1 = tmp2 = weird_local_var = 0;

If I write like below, it does not happens

var normal_local_var = 0;

It is not because tmp1 & tmp2, just dummy var for testing. You can see the test via http://jsfiddle.net/7SeRD/. What happen?

StoneHeart
  • 15,790
  • 32
  • 67
  • 84

2 Answers2

3

You can just change your init line to:

var tmp1=0, tmp2=0, weird_local_var=0, normal_local_var=0;

// or
var tmp1=0; 
var tmp2=0;
var weird_local_var=0;
var normal_local_var=0;

EDIT: See this answer too: link.

From it:

var a = b = [] is equivalent to

var a;
b = [];
a = b;

What you're doing is chaining assignments.

You're essentially assigning a reference to weird_local_var (whose value is 0) to tmp2, then assigning a reference to that reference (ie tmp1 -> tmp2) to tmp1.

Community
  • 1
  • 1
Josh
  • 12,448
  • 10
  • 74
  • 118
1

You are creating v2 and weird_local_var as globals by not using the "var" keyword when you declare them.

try the same thing creating the variables beforehand and it will work as expected: http://jsfiddle.net/MaxPRafferty/2MKgH/

        var v2;
        var weird_local_var;
        var v1 = v2 = weird_local_var = 0;
MaxPRafferty
  • 4,819
  • 4
  • 32
  • 39