英文:
Confused about comma separated functions looking at chrome extension code
问题
I can translate the code-related content for you:
chrome.runtime.onMessage.addListener((o, s, c) => {
c(),
(function(o, s, c) {
<code>
})
(o.url, o.headers)
});
这部分代码的问题在于,为什么前两个语句之间使用逗号分隔,而第三个语句被括在括号中。如果移除逗号,将会在控制台中出现错误:
事件处理程序中的错误:TypeError:c(...) 不是一个函数
这似乎是将第三个函数与逗号后面的函数关联起来的方式。这并不是唯一出现这种情况的地方。在 background.js 中,chrome.webRequest.onSendHeaders.addListener()
和下一个函数 chrome.runtime.onMessage.addListener()
之间也用逗号分隔:
chrome.webRequest.onSendHeaders.addListener(
<code>
),
chrome.runtime.onMessage.addListener(
<other code>
)
我希望这能解释一下这种写法。
英文:
I'm attempting to learn more about chrome extensions and the best way I learn is by looking at stuff that works and trying to understand what it is doing. Well I've gotten a decent understanding of one I've been looking at but I see quite a few odd things that I'm not really sure why they are written that way. Here is a snippet of what I'm looking at:
chrome.runtime.onMessage.addListener((o, s, c) => {
c(),
(function(o, s, c) {
<code>
})
(o.url, o.headers)
});
What I don't understand is why the first 2 statements are separated by a comma while the 3rd is just wrapped in parenthesis. If I remove the comma, then there is an error in the console stating
> Error in event handler: TypeError: c(...) is not a function
It almost seems like somehow that is linking the c function with the function after the comma. I really don't know what is happening with it and it's not the only place that I see it. In the background.js the chrome.webRequest.onSendHeaders.addListener()
is separated by a comma from the next function of chrome.runtime.onMessage.addListener()
chrome.webRequest.onSendHeaders.addListener(
<code>
),
chrome.runtime.onMessage.addListener(
<other code>
)
Tried to look up as best I could but couldn't quite find anything that answered my question. Can anyone explain it to me?
答案1
得分: 1
以下是已翻译的内容:
这基本等同于这段代码:
最小化的代码在语句之间使用逗号操作符而不是分号。
它使用了IIFE来为<code>
创建了一个嵌套的变量作用域。(o.url, o.headers)
是IIFE的参数。在现代的ES6语法中,这可以使用块和let
变量绑定来完成。
我将监听器的o
参数重命名为o1
,以避免与嵌套块中的o
变量发生冲突。
英文:
This is essentially equivalent to this code:
The minified code is using the comma operator instead of semicolon between statements.
It's using an IIFE to create a nested variable scope for <code>
. (o.url, o.headers)
are the arguments to the IIFE. In modern ES6 syntax this can be done using a block and let
variable bindings.
I've renamed the o
parameter to the listener to o1
so it doesn't conflict with the o
variable in the nested block.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
chrome.runtime.onMessage.addListener((o1, s, c) => {
c();
{
let o = o1.url;
let s = o1.headers;
let c;
// <code>
}
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论