This is from node-webworker in node.js. The code works as advertised, but I don't understand how.
In master.js
the web worker is created (as w
), and it has w.onmessage = function...
.
But in foo.js
which defined the web worker, there is already an onmessage = function...
.
I'm missing something fundamental, but the question is: why doesn't the master.js
w.onmessage
overwrite the original foo.js
onmessage
?
master.js
var sys = require('sys');
var Worker = require('webworker');
var w = new Worker('foo.js');
w.onmessage = function(e) {
sys.debug('Received mesage: ' + sys.inspect(e));
w.terminate();
};
w.postMessage({ foo : 'bar' });
foo/foo.js
var sys = require('sys');
onmessage = f开发者_JAVA百科unction(e) {
postMessage({ test : 'this is a test' });
};
onclose = function() {
sys.debug('Worker shutting down.');
};
If you have a module with code like this:
func = function() {
console.log('function called');
};
And require it like this:
var module=require('./module');
Then module.func
will be undefined
. That's because func
is assigned to the module's global scope. When you call require
, you get a reference to the module's exports
, not the module's globals. Thus, when you set module.func
, say, like this:
module.func = function() {
console.log('was it overwritten?');
};
...then the module's exports
will indeed reflect the new function, but it never touched the module's globals.
Because when you make changes in instance of object you don't change his prototype (class) (read about js object model). If you want to change behavior of parent object then type this:
w.prototype.onmessage = function() {/* ...your code... */};
JS Object Model lets you to overwrite every object's method to change it's behavior but safe prototype from this change. Get used.
When you load module it runs in isolated scope, so you couldn't get access to sys functions without direct change required object. That will help you to understand nodejs' module model, try to run it:
require.js
module.exports = {};
main.js
var x = require('./require.js');
x.tell = true;
var y = require('./require.js');
y.tell = false;
console.log(require('./require.js'));
精彩评论