简体   繁体   中英

Strange JavaScript Function Call Construct (0, <function>)()

Code in the wild:

return function decorateSource(DecoratedComponent) {
    return (0, _decorateHandler2.default)({
        connectBackend: function connectBackend(backend, sourceId) {
            return backend.connectDragSource(sourceId);
        },
        containerDisplayName: 'DragSource',
        createHandler: createSource,
        registerHandler: _registerSource2.default,
        createMonitor: _createSourceMonitor2.default,
        createConnector: _createSourceConnector2.default,
        DecoratedComponent: DecoratedComponent,
        getType: getType,
        collect: collect,
        options: options
    });
};

And the construct in question:

(0, _decorateHandler2.default)(...)

What is going on with this wrapped statement?

It's similar to doing this:

(function(){
    // do something
})();

In that because the element is wrapped in parentheses gets treated as a value, and the last value in the parentheses is being executed as a function by the following parentheses. The 0, isn't doing anything. Removing 0, won't change how the code is run, so in this case I figure 0, is just obfuscation as whatever _decorateHandler2.default returns is what decorateSource returns. The benefit of doing this (or the code sample above) is that you're creating a closure that help you control the scope of your variables and not pollute the global scope.

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