Question

Simply speaking I am trying to prototype a function within a web worker and chromium is throwing this error:

Uncaught TypeError: Object #<DedicatedWorkerContext> has no method 'compute'

I figure some sample code is needed. It is the end of my work day, so I am throwing this together real quick. It's been boggling me all afternoon. I am hoping its one of those problems I come back tomorrow morning and say "ah-hah" but on the off chance I wont, I thought I'd ask here too.

page.js

function threaded() { 
   var thread = new Worker('worker.js');
   thread.postMessage({a: 1 b: 2});
   thread.onMessage = function (e) { 
     console.log(e.data)
   });
}
threaded();

worker.js

var foo = function(a,b) { 
   this.a = a
   this.b = b
   this.result = false;
   this.compute();
};

foo.prototype.compute = function() { 
   this.result = this.a * this.b;
};

onmessage = function(e) { 
   var msg = foo(e.data.a,e.data.b)
   postMessage(msg)
};

I've also tried arraigning worker.js differently to include foo() within onmessage as follows, but received the following error:

Uncaught TypeError: Cannot set property 'a' of undefined

worker-take2.js

onmessage = function(e) { 

   var foo = function(a,b) { 
      this.a = a
      this.b = b
      this.result = false;
      this.compute();
    };

   foo.prototype.compute = function() { 
     this.result = this.a * this.b;
   };

   var msg = foo(e.data.a,e.data.b)
   postMessage(msg)
};
Était-ce utile?

La solution

The issue is that you're executing foo, rather than declaring a new instance of it. Thus, this within the context of foo evaluates to the dedicated worker context, rather than the object instance context.

Try this out:

var foo = function(a,b) { 
   this.a = a
   this.b = b
};

foo.prototype.compute = function() { 
   return this.a * this.b;
};

onmessage = function(e) { 
   var msg = new foo(e.data.a,e.data.b).compute();
   postMessage(msg)
};

There's a few important changes to be aware of. Firstly, I changed compute to return the result, rather than set it as a property. Remember, when using prototype you're explicitly creating methods that are shared across object instances, thus implying your use of that code in an object oriented fashion.

Second, I changed the constructor of foo so that it doesn't call compute immediately. Instead, compute is called after declaring an object instance.

Try it out!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top