繁体   English   中英

如何理解这样的箭头函数?

[英]How to understand such arrow function?

if ((() => {
    let hasChrome = false;
    let hasBrowser = false;
    try {
        hasChrome = (typeof chrome === 'object' && chrome !== null && typeof chrome.runtime !== 'undefined');
    } catch (e) {
        // NOP
    }
    try {
        hasBrowser = (typeof browser === 'object' && browser !== null && typeof browser.runtime !== 'undefined');
    } catch (e) {
        // NOP
    }
    return (hasBrowser && !hasChrome);
})()) {
    chrome = browser;
}

上面的代码似乎是一个箭头 function,但我想知道 function 的名称在哪里? 怎么理解?
不应该像这样箭头 function 吗?
hello = () => { return "Hello World;"; }

任何帮助都非常感谢,并提前感谢。

当您以片段中显示的方式使用箭头函数时,它们也是匿名的。 此外,我们使用称为立即调用的 Function 表达式 (IIFE)的东西,这样箭头 function 的返回值作为条件传递。

通常来说,一般来说,

() => { return "Hello World!"; }

这是箭头 function

hello = () => { return "Hello World!"; }

在这里,箭头 function 被分配给变量“hello”,以便可以像 hello() 一样引用它。

箭头函数不一定要分配,也可以匿名调用。

例如:

promise.then(()=>{console.log('hello world')});

这里箭头 function 在 promise 之后立即执行。

function 没有名称。 它是匿名的,它会立即执行。 如果仔细观察,可以看到整个 function 都包裹在括号中
这个

(
  ()=>{
   // do stuff
   return null
  }
)()

和这个一样

(
  function(){
    //do stuff
    return null
   }
)()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM