我遇到了如下代码。
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
可能是分别用参数message
和plaintext, 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.