0

I know that if you exclude the var keyword, JS will search parent scopes

However, I see people assigning multiple vars like:

var a = 3,
    b = 2;

and I'm assuming this type of assignment doesn't look through parent scopes.

Am I correct in assuming this, and would this example behave the same, or check parent scopes:

this.a = 3,
    b = 2;
neaumusic
  • 8,193
  • 7
  • 41
  • 65
  • 1
    `var` accepts from 1 to ∞ variable names. Object property access is strictly one object and one property. The second example assigns `3` to `this.a` and `2` to `b`. – zerkms Nov 30 '15 at 23:49

2 Answers2

2

The two constructs you posted do completely different things.

var a = 3,
    b = 2;

In the above, the var statement allows , to specify multiple var's in one. It is equivalent to;

var a = 3;
var b = 2;

In the second snippet you posted, you are setting the a property of this to 3, then (using the comma operator) assigning the variable b (which will involve searching the parent scopes to find a declaration of b) to 2.

For more information, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Comma_Operator

Matt
  • 70,063
  • 26
  • 142
  • 172
1

No, you're not correct. this. has nothing to do with scopes; rather, this is an object and .a is a property access. This is not a declaration of any kind, it's just an assignment, which is separated by a comma from another assignment:

b = 2

and that assignment will search the scope chain as usual.

In contrast, the multiple variable declaration uses commata to separate names (the initialisers are optional). It's equivalent to

var a, b;
a = 3;
b = 2;
Bergi
  • 513,640
  • 108
  • 821
  • 1,164