user699242
user699242

Reputation: 1833

JavaScript namespacing and object creation

I'm trying to figure out why you might use the following code:

    var myObject = myObject || {};

I've seen this used several times, but don't understand why this would be necessary. Thanks for your responses.

Upvotes: 3

Views: 136

Answers (3)

r3joe
r3joe

Reputation: 46

This technique is called "Short-circuit" evaluation.

hort-circuit evaluation, minimal evaluation, or McCarthy evaluation denotes the semantics of some Boolean operators in some programming languages in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true

http://en.wikipedia.org/wiki/Short-circuit_evaluation

Upvotes: 0

Ruan Mendes
Ruan Mendes

Reputation: 92274

People call JavaScript's binary or || the defaulting operator

var myObject = myObject || function(){};

is the same as

var myObject = myObject ? myObject : function(){};

The following code

var AppSpace = AppSpace || {};

is used because multiple files are going to set and use the namespace, and you don't want to overwrite the namespace if it has already been created. That way, it doesn't matter which file is included first.

Here's another example of defaulting.

function doSomething (callback)  {
   something();
   code();      
   callback = callback || function() {};
   // Now we can call the callback even if it wasn't passed in.
   callback();         
}

However, be careful of the following problem Why does IE nuke window.ABC variables?

That is if a namespace has been defined using

window.AppSpace = {a: 1};

And another file sets

var AppSpace = AppSpace || {}

In IE, it will overwrite the value of window.AppSpace to the empty object if the two scripts are in different script tags because of variable hoisting and the fact that IE doesn't realize that window.a and var a at the top level are all pointing at the same variable.

Upvotes: 4

Andrew Latham
Andrew Latham

Reputation: 6132

function(){} is an empty class since classes are functions in JavaScript. This code in particular is taking advantage of the early-exit from OR in JavaScript - it evaluates the first item, and sets the result equal to that if it's truthy and equal to the second item if it's falsy. So if myObject is truthy (not null), myObject equals that, and if it's not then it equals an empty function.

Basically, what this code is saying is "if myObject is already something, leave it where it is, and otherwise make it equal to this blank function".

Upvotes: 2

Related Questions