JavaScript StructuredClone 在 Chrome/Edge 中遇到“非法调用”,但在 NodeJS 中没有遇到问题

问题描述 投票:0回答:1

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

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

将会得到

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

但是在 NodeJS 中运行代码没问题,在 NodeJS v20 中进行了测试。

解决方法:

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

或者

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

这是预期的行为吗?

javascript node.js browser structured-clone
1个回答
0
投票

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

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

所以浏览器中的

structuredClone
需要在
window
上下文中执行:

structuredClone.call(window, 1);

// hmm, works with null too
structuredClone.call(null, 1);

structuredClone.call(1, 1);

© www.soinside.com 2019 - 2024. All rights reserved.