var app = app || {}

看 TODOMVC 源代码的时候,看到如下一段代码:

var app = app || {};

https://github.com/tastejs/todomvc/blob/master/examples/backbone/js/models/todo.js#L2

很多次看到过类似的代码,也大概明白这是怎么回事,可是,为啥要这么写,这么写是怎么起作用的呢?

在 StackOverflow 上,也有带着类似困惑的小伙伴问了类似的问题,这里:
http://stackoverflow.com/questions/6439579/what-does-var-foo-foo-assign-a-variable-or-an-empty-object-to-that-va
“标准答案”是这么解释的:

Your guess as to the intent of || {} is pretty close.

This particular pattern when seen at the top of files is used to create a namespace, i.e. a named object under which functions and variables can be created without unduly polluting the global object.

The reason why it's used is so that if you have two (or more) files:

var MY_NAMESPACE = MY_NAMESPACE ||  {};
MY_NAMESPACE.func1 = {}

and

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func2 = {}

both of which share the same namespace it then doesn't matter in which order the two files are loaded, you still get func1 and func2 correctly defined within the MY_NAMESPACE object correctly.

The first file loaded will create the initial MY_NAMESPACE object, and any subsequently loaded file willaugment the object.

Usefully, this also allows asynchronous loading of scripts that share the same namespace which can improve page loading times. If the

你可能感兴趣的:(var app = app || {})