Javascript object creation?

Possible Duplicate:
What does “var FOO = FOO || {}” mean in Javascript?

I am finding this kind of statement in javascript object creation repeatedly.

 var MyObj = MyObj || {};

Could some one could explain the significance of the above statement?

why can't we create just

var MyObj = {};

Thanks.


var MyObj = MyObj || {};

That simply says "if MyObj already exists and has a truthy value, keep it; otherwise, create a new object". It's a common way of doing optional parameters to functions, for example.

See MDN's page on logical operators for more information on the subject.


What if MyObj already exists.

If it alreay exists .. the statement

var MyObj = {} resets the object (which is bad)

Hence it is usually done with ||

If it already exists, preserve whatever it is ... else create a new object.

The || operator says:

this || that this || that -> this OR that

So in your example

myObj is myObj or new Object if myObj isn't defined or set to falsy value ( null, 0, "", false, undefined )


That means that if MyObj is evaluated to false (ie it is null or undefined) then create a new object. It is a short form that leverage the fact that if MyObj is evaluated to true when casted to boolean (ie it is not null and defined) the second part of the OR expression is not evaluated.

链接地址: http://www.djcxy.com/p/95294.html

上一篇: 构建一个HTML5游戏

下一篇: Javascript对象创建?