如何在web worker中使用 JSON.stringify 方法,以及 ES2015 的 Object.keys 等扩展方法

worker独立于window对象且不能访问dom及相关方法,但除此之外,最近发现在web worker中不能使用很多常见方法。比如JSON.stringify、Object.keys、Object.assign、Object.values等等

通过console.log打输出可以确定worker内是可以获取到这些方法的。

但实际执行是会输出如下报错。

ReferenceError: _stringify2 is not defined
    at blob:http://localhost:8080/321543fe-b62e-41bf-abf7-2e2da6770ada:4
blob:http://localhost:8080/321543fe-b62e-41bf-abf7-2e2da6770ada:11

ReferenceError: _keys2 is not defined
    at blob:http://localhost:8080/321543fe-b62e-41bf-abf7-2e2da6770ada:9
blob:http://localhost:8080/321543fe-b62e-41bf-abf7-2e2da6770ada:16

ReferenceError: _values2 is not defined
    at blob:http://localhost:8080/321543fe-b62e-41bf-abf7-2e2da6770ada:14

我的浏览器是Chrome最新版本

相关代码

worker中执行:

  console.info('way-finding worker init.')
  try {
    console.info(JSON.stringify)
  } catch (e) {
    console.info(e)
  }
  try {
    console.info(Object.keys)
  } catch (e) {
    console.info(e)
  }
  try {
    console.info(Object.values)
  } catch (e) {
    console.info(e)
  }

不清楚是否我worker的使用有问题,期望有朋友能指点下,谢谢。

阅读 3.3k
2 个回答

完全可以啊
clipboard.png

看你的这个报错里的一些keys都被转化了 可能你用了什么构建工具(比如babel) 编译了的代码不如你的预期
查看你编译后的代码

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题