变量名 = ()() 是什么意思?

6
我遇到了以下代码。
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(立即调用函数表达式),但我不明白行末的括号具体起什么作用或者它们在做什么。
有谁能帮我理解一下吗?

1
这是一个IIFE,并且看起来像是已编译的代码。在修改之前,请检查它是否是生成/编译代码,因为如果是,源代码将更容易阅读。如果这就是源代码,则括号中的值是要调用该函数的值。 - Justin Mitchell
我最初并不知道它是生成/编译的代码。然后我检查了一下,发现确实是这样。我找到了源代码,阅读起来确实更容易。正如另一个回答中的mrlew所提到的_getURLJWT(message)一样。感谢您的评论。 - Gem Cutter
1个回答

4

_getURLJWT_encryptMessage 可能是被分别调用并传入参数 messageplaintext, pubEncKey 的函数。

在 JavaScript 中,当你使用逗号操作符将两个值隔开时,会对所有操作数进行评估,并返回最后一个结果。因此,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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接