我使用创建了一个Web worker,但是找不到从Worker函数内部获取Worker实例的方法。
从函数内部,如果我使用“ this”或“ self”,则只能获得“ DedicatedWorkerGlobalScope”对象。
请查看下面的代码片段以了解问题所在:
/******** below is main.html file *********/
var mywebworker1 = new Worker('mywebworker1.js');
// register event listener to receive data from worker
mywebworker1.addEventListener('message', function(e) {
// at this point, 'this' == 'Worker' instance
// ... other code
});
/******** below is inside mywebworker1.js file *********/
self.addEventListener('message', function(e) {
// at this point, 'this' == 'DedicatedWorkerGlobalScope' object
// PROBLEM: How to get 'Worker' instance in here ??
// .. other code
}, false);
我试图在postMessage中传递Worker实例,例如:
// send command to start counting
mywebworker1.postMessage({"action": "count", "from" : 7, "to": 22, "instance": mywebworker1});
// GOT ERROR message = Uncaught DOMException: Failed to execute 'postMessage' on 'Worker': Worker object could not be cloned.
预先感谢您的帮助〜