【问题标题】:JavaScript: understanding void 0 in ?? operator polyfill [duplicate]JavaScript:理解 void 0 in ??运算符 polyfill [重复]
【发布时间】:2021-05-17 17:10:59
【问题描述】:

我很好奇 null 合并运算符 ?? 在默认 create-react-app 设置中是否有一个 polyfill。事实证明确实如此:

const App = () => {
    const foo = 'custom value';

    return (
        <div>
            {foo ?? 'default value'}
        </div>
    );
};

变成:

const App = () => {
  const foo = 'custom value';
  return /*#__PURE__*/Object(react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__["jsxDEV"])("div", {
    children: foo !== null && foo !== void 0 ? foo : 'default value'
  }, void 0, false, {
    fileName: _jsxFileName,
    lineNumber: 7,
    columnNumber: 9
  }, undefined);
};

最有趣的部分是foo !== null &amp;&amp; foo !== void 0 ? foo : 'default value',它是?? 操作符的polyfill。虽然foo !== null 很明显,但我不太明白foo !== void 0 部分。什么意思?

我查了一下,void 0 === undefinedtrue,但为什么不是简单的foo !== undefined

【问题讨论】:

    标签: javascript reactjs null-coalescing-operator


    【解决方案1】:

    void 0undefined 相同,大部分时间。使用void 0 有两个好处:

    • 它更短(这对缩小器很有用)

    • 标识符undefined不在顶层时可以创建,导致意外行为:

    (() => {
      const undefined = 'foo';
    
      // later in the code:
    
      const actuallyUndef = (() => {})();
      console.log(actuallyUndef === undefined);
    })();

    这是一个非常病态的案例,但使用void 0 会更安全一点。

    古代浏览器过去也允许在顶层创建undefined,但幸运的是不再允许。

    【讨论】:

    • 看,我不知道你可以在函数内部覆盖undefined!我认为现代浏览器只是不允许它,但你是对的!在函数内部覆盖 undefined 确实有效,即使在严格模式下也是如此。
    猜你喜欢
    • 2023-03-29
    • 2011-08-10
    • 2016-09-05
    • 2015-07-25
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2015-06-13
    相关资源
    最近更新 更多