Skip to content Skip to sidebar Skip to footer

Confusing Use Of Commas And Newlines In Variable Assignment Expression Makes Var Look Global

Update: it was really the comma before the that variable assignment which threw me off, not so much about any patterns. (don't use this notation. see https://stackoverflow.com/a/

Solution 1:

They aren't declaring global variables, they're declaring closure variables. Every function definition you attach to that is a closure (provided it uses a variable from the surrounding scope).

Example:

functioncreateObj() {
  var that = {}; // Not global but will be used in a closure
  that.name = 'Bob';
  that.doSomething = function() {
    return that.name; // Used as a closure variable
  };
  return that; // Return a new object, not a global one
}

They're applying the same principle except they're also creating a separate object, _privateObj which is never directly exposed. This lets you have private data and methods which no one else can access.

You might think they're declaring a global due to the different syntax for declaring multiple variables.

This:

var a = 1,
    b = 2;

is equivalent to this:

var a = 1;
var b = 2;

Notice the use of the , in the previous example. That allows you to declare multiple variables in a single var statement.

Solution 2:

Your //wtf's code means:

var that = newObject();

Post a Comment for "Confusing Use Of Commas And Newlines In Variable Assignment Expression Makes Var Look Global"