在浏览器中运行以下代码:
({ 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);
这是预期的行为吗?
似乎是特定于平台的。 如果您在 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);