小编Cha*_*ord的帖子

Node.js将具有函数定义的对象发送到工作线程

所以我正在开发Node.js中的一个项目,我想打开一些额外的线程来更有效地处理处理负载.但是我正在使用带有函数定义的类,当我尝试将这些对象发送到工作线程时,对象中定义的函数会消失,而我只剩下对象中的其他字段.有没有办法向worker发送一个对象并保留这些函数,以便可以在worker中调用它们?

var cluster = require('cluster');

if(cluster.isMaster){
    Monster = function(species){
        this.attack = function(){
            console.log('CHOMP');
        };
        this.name = species;
    };
    var vamp = new Monster('vampire'),
    worker   = cluster.fork();
    worker.send({'monster' : vamp});
    }
else{
    process.on('message', function(msg) {
        console.log(msg.monster); //this logs "{ name: 'vampire' }"  
        msg.monster.attack(); //TypeError: Object #<Object> has no method 'attack'
    });
}
Run Code Online (Sandbox Code Playgroud)

multithreading function cluster-computing worker node.js

8
推荐指数
1
解决办法
3404
查看次数