gpt4 book ai didi

namespaces - Web Worker importScripts 无法将脚本变量置于全局范围内

转载 作者:行者123 更新时间:2023-12-04 17:01:29 27 4
gpt4 key购买 nike

TL;DR 我有一个 worker 通过 importScripts 导入两个对象。它们不会出现在“自我”中。 Moz 文档说:

        importScripts() method of the WorkerGlobalScope interface 
synchronously imports one or more scripts into the worker's scope.

那么他们在哪里?!

细节:
三个文件:index.html、worker.js、foo.js

index.html 包含:
const worker = new Worker('./worker.js')
worker.postMessage({ file: './foo.js', var: 'foo' })

worker.js 包含:
onmessage = e => {
params = e.data
console.log('worker: params', params)
console.log('worker: this === self', this === self)
importScripts(params.file)
console.log(self[params.var], eval(params.var), foo)
}

foo.js 包含:
const foo = { one: 1, two: 2 }
const bar = { three: 3, four: 4 }

IE。 html 将路径和变量名称传递给导入路径的工作程序,并使用变量名称尝试在“self”中找到它。失败。

然而,使用“eval”或变量本身,而不是它的名称,可以按预期工作。

以下是控制台消息:
worker: params {file: "./foo.js", var: "foo"}
worker: this === self true
undefined {one: 1, two: 2} {one: 1, two: 2}

那么worker把从foo.js导入的变量放在哪里呢?!

注意:这似乎是一件奇怪的事情,为什么不直接使用变量呢?存在与高度(重新)分解的 repo 有关的深层原因。

最佳答案

使用 constlet声明变量不会将它们添加到全局作用域对象中,例如 worker selfwindow (见 MDN description for const)。使用 var但是:

const x = 1;
let y = 2;
var z = 3;

console.log(window.x, window.y, window.z);
// undefined undefined 3

更改 foo 的变量声明和 bar使用 var应该解决问题。

关于namespaces - Web Worker importScripts 无法将脚本变量置于全局范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com