if nativeWindow evaluates to false (e.g. if it's undefined) then appjs is passed in as source; otherwise nativeWindow is passed in as source. The property onmessage of whichever object ispassed in as source is then set to the onmessage function
|| and onmessage in javascript
-
28-06-2022 - |
Question
I am reading a open source project and it has a js file like this
var pipe = function(source, listeners){
source.onmessage = function onmessage(msg){
//.. do something ..
};
return {
//.. something ...
};
}(nativeWindow || appjs, {});
What does (nativeWindow || appjs )
means where they both are objects ?
Does it mean that this function is called for both of them ?
Or it is merging both of these objects ?
And is this .onmessage
is something standard thing like alert()
or window
? What i mean by standard is that is there something happening behind the scenes in this .onmessage
function or is it just like simple function ?
Thanks
Solution
OTHER TIPS
From the MDN :
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
In this specific case, the first value whose value is defined is passed as argument.
.onmessage
is whatever it is assigned in the pipe
function. It is just a normal property on the source
object.
The ||
and &&
in javascript returns a value.
This means; nativeWindow
OR appjs
gets passed in, as the returned value from the expression; the last evaluated expression gets returned. If nativeWindow
is a falsy (null, undefined etc) value, appjs gets passed in. If nativeWindow
is thruthy (e.g. an object) it gets passed in. Just think this OR that
. If both values are falsy, the one on the right hand side will still be passed in. Read more on || and && here: http://www.grauw.nl/blog/entry/510
||
is the OR
operator. It also short-circuits if the left-hand evaluates is true-ish. So what it does is provide the function with either the value of nativeWindow
OR appjs
if nativeWindow
is false-ish.
A more verbose of the same would be:
var pipe = function()...;
if(nativeWindow) {
pipe = pipe(nativeWindow);
} else {
pip = pipe(appjs);
}
(nativeWindow || appjs, {}) = (source, listeners)
They are the parameters passed
nativeWindow || appjs
means if nativeWindow is undefined or falsy take the value of appjs
source.onmessage
onmessage is the property of the object source (passed as nativeWindow || appjs
) which holds a function in your case