ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – ‘self’关键字在WebWorkers中意味着什么

2019-05-28 10:20:27  阅读:218  来源: 互联网

标签:javascript self web-worker


我不明白7,8,9行:

var worker = new Worker('doWork.js');

worker.addEventListener('message', function(e) {
  console.log('Worker said: ', e.data);   // Here it send's the data.
}, false);

worker.postMessage('Hello World'); // Send data to our worker.



 //7 self.addEventListener('message', function(e) {
   //8   self.postMessage(e.data);
   //9 }, false);

做这段代码的是什么?
1.什么代码行在第7行触发消息事件?
2.在第8行的postMessage中传递了什么数据?
3.自我做什么?

解决方法:

关键字self用于接近Worker的API,这意味着无论范围(即使它是一个闭包),您都可以访问Worker的API(我不确定您是否可以将self重新声明为其他内容并且松散Worker的API引用,但我相信它受JS保护,因此您无法覆盖它).

以下几行:

self.addEventListener('message', function(e) {
    self.postMessage(e.data);
}, false);

只是为’message’事件添加一个事件监听器,它将事件中的数据发送回webworker在其产生的上下文中的引用(最常见的是当前浏览器线程或父工作者).我们可以引用false布尔值确定的内容:

useCapture Optional If true, useCapture indicates that the user wishes
to initiate capture. After initiating capture, all events of the
specified type will be dispatched to the registered listener before
being dispatched to any EventTarget beneath it in the DOM tree. Events
which are bubbling upward through the tree will not trigger a listener
designated to use capture. See DOM Level 3 Events and JavaScript Event
order for a detailed explanation. If not specified, useCapture
defaults to false.

Note: For event listeners attached to the event
target; the event is in the target phase, rather than capturing and
bubbling phases. Events in the target phase will trigger all listeners
on an element regardless of the useCapture parameter.

Note: useCapture
became optional only in more recent versions of the major browsers;
for example, it was not optional prior to Firefox 6. You should
provide this parameter for broadest compatibility.

  
  wantsUntrusted如果为true,则侦听器将接收合成事件
  由web内容调度(chrome的默认值为false,为true
  对于常规网页).此参数仅在Gecko和
  主要用于附加组件和浏览器本身的代码.看到
  特权页面与非特权页面之间的交互
  例.

来自:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

关键字self的更多技术说明:

The self read-only property of the WorkerGlobalScope interface returns
a reference to the WorkerGlobalScope itself. Most of the time it is a
specific scope like DedicatedWorkerGlobalScope,
SharedWorkerGlobalScope, or ServiceWorkerGlobalScope.

引自:https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self

标签:javascript,self,web-worker
来源: https://codeday.me/bug/20190528/1170201.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有