简体   繁体   中英

JavaScript define var shorthand for object of uncertain state

这是什么意思?

var ourObject = ourObject || {};

In answer to "What does it mean?", the code above is equivalent to:

var ourObject;
if(scope.ourObject) {
    ourObject = scope.ourObject;
}
else {
    ourObject = {};
}

Where scope above is the current scope of the block of code (by default, window ).

And it means if this object (ourObject) does not exist in the current scope, create it and assign it to the local variable ourObject . It ensures that ourObject will never be undefined in the current scope.

There's not much context here, but this idiom is often seen within functions:

function name (param) {
    param = param || 'default value';
    // now you can be sure that param has a non-null value
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM