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!