What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript?

前端 未结 7 2182
野性不改
野性不改 2020-11-22 02:07

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 ide

7条回答
  •  忘掉有多难
    2020-11-22 02:48

    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, i.e. 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

提交回复
热议问题