var name = ()() 是做什么的?

What does var name = ()() do?

我遇到了如下代码。

return new Promise(function (resolve, reject) {
      if (!message) return reject(new Error('Requires message request to send'));
      message = (0, _getURLJWT)(message);
      .....
      .....
      var enc = (0, _encryptMessage)(plaintext, pubEncKey);

      }, function (error, res, body) {
       ....
       ....
      });
    });

我不明白代码中的两个表达式:

message = (0, _getURLJWT)(message);
var enc = (0, _encryptMessage)(plaintext, pubEncKey);

这看起来像 IIFE(立即调用的函数表达式),但是,我不明白该行末尾的括号是如何工作的或者它们在做什么。

谁能帮我理解一下?

_getURLJWT_encryptMessage 可能是分别使用参数 messageplaintext, pubEncKey 调用的函数。

当您写入两个由逗号运算符分隔的值时,Javascript 计算其所有操作数并 returns 最后一个。所以 0, 1 将评估 1.

因此,(0, _getURLJWT)(message) 将计算为 _getURLJWT(message)

例如:

console.log((0,1)); //1

(0, (myArg) => console.log(myArg))('hello'); //hello

使用此技术的原因

以这种方式调用可确保调用函数时 this 设置为全局对象。

const myObj = {
    printMe: function() { console.log(this); },
}

myObj.printMe(); //{printMe: ƒ}

(0, myObj.printMe)(); // Window {parent: Window, opener: null...} <= loses reference, the this will not longer be bound to myObj, but will be bound to the global object.