{}" (assign a variable or an empty object to that variable) mean in Javascript?
Looking at an online source code I came across this at the top of several source files.
var FOO = FOO || {};
FOO.Bar = …;
But I have no idea what || {}
|| {}
does.
I know {}
is equal to new Object()
and I think the ||
is for something like "if it already exists use its value else use the new object.
Why would I see this at the top of a source file?
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, ie 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 will augment the object.
Usefully, this also allows asynchronous loading of scripts that share the same namespace which can improve page loading times. If the <script>
tags have the defer
attribute set you can't know in which order they'll be interpreted, so as described above this fixes that problem too.
var AEROTWIST = AEROTWIST || {};
Basically this line is saying set the AEROTWIST
variable to the value of the AEROTWIST
variable, or set it to an empty object.
The double pipe ||
is an OR statement, and the second part of the OR is only executed if the first part returns false.
Therefore, if AEROTWIST
already has a value, it will be kept as that value, but if it hasn't been set before, then it will be set as an empty object.
it's basically the same as saying this:
if(!AEROTWIST) {var AEROTWIST={};}
Hope that helps.
Another common use for || is to set a default value for an undefined function parameter also:
function display(a) {
a = a || 'default'; // here we set the default value of a to be 'default'
console.log(a);
}
// we call display without providing a parameter
display(); // this will log 'default'
display('test'); // this will log 'test' to the console
The equivalent in other programming usually is:
function display(a = 'default') {
// ...
}
链接地址: http://www.djcxy.com/p/2794.html