代码之家  ›  专栏  ›  技术社区  ›  DiscreteTom

JavaScript structuredClone在Chrome/Edge中获得了“非法调用”,但在NodeJS中没有

  •  1
  • DiscreteTom  · 技术社区  · 1 年前

    在浏览器中运行以下代码:

    ({ clone: structuredClone }).clone(1);
    

    将得到 Uncaught TypeError: Illegal invocation ,在Chrome/Edge中进行了测试。

    然而,在NodeJS中运行代码是很好的,在NodeJSv20中进行了测试。

    解决方法:

    ({ clone: (v) => structuredClone(v) }).clone(1);
    

    ({ clone: function(v) { return structuredClone(v)} }).clone(1);
    

    这是预期的行为吗?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Alexander Nenashev    1 年前

    似乎是特定于平台的。 如果你在Firefox中运行,你会得到一个更具描述性的错误:

    Uncaught TypeError: 'structuredClone' called on an object that does not implement interface Window.
    

    所以 structuredClone 在浏览器中需要在中执行 window 上下文在浏览器中,可以有多个窗口(iframe)作为全局上下文,而不是只有一个的Node。所以 结构化克隆 应该知道在哪个窗口采取行动。

    structuredClone.call(window, 1);
    
    // hmm, works with null too, seems takes the current window
    structuredClone.call(null, 1);
    
    structuredClone.call(1, 1);
    推荐文章