Can somebody please tell me what || this doing here
(function()
{
window.myapp = window.myapp || {};
window.myapp.lang = window.myapp.lang || {};
myapp.lang.Extend = function(subClass, superClass)
{
subClass.prototype = new superClass();
};
})();
Can somebody please tell me what || this doing here
(function()
{
window.myapp = window.myapp || {};
window.myapp.lang = window.myapp.lang || {};
myapp.lang.Extend = function(subClass, superClass)
{
subClass.prototype = new superClass();
};
})();
window.myapp = window.myapp || {};
It means: create window.myapp as an empty object if it does not already exist.
The a = a || b;
syntax is equivalent to
if (!a)
a = b;
or
a = a ? a : b;
window.myapp = window.myapp || {};
is equivalent to this code
if(!(window.myapp)) {
window.myapp = {};
}
||
is the logical OR operator in Javascript.
In this case
window.myapp = window.myapp || {};
assigns window.myapp
to itself if it is not null or false, otherwise it assigns an empty object {}
to window.myapp
.
|| is a short-circuiting operator
while evaluating x || y , x is evaluated first, if it is true - then there is no need to evaluate y because the operation is anyway going to be true.
in javascript the following values result in 'false' when used as if condition -
0 -0 null "" false undefined NaN
so in your case if window.myapp is 'undefined', that will be evaluated to 'false', and the or operator has to evaluate the next operand {} to complete the operation, which is assigned to window.myapp
so all it is doing is -
if(!(window.myapp)) {
window.myapp = {};
}