自定义类与自定义事件和asynchronous工作通过浏览器使用

我创build了一个简单的类与asynchronous工作和自定义事件。 这个版本适用于Node.js:

'use strict'; const EventEmitter = require('events'); // Custom class with the custom event and async work class Foo extends EventEmitter{ // Some async work with notifying doWork(data){ const self = this; if(!data || 'number' != typeof data) { self.emit('work-done', new Error('Invalid data')); return; } else{ // Some long work... function fib(n){ return n < 2 ? n : fib(n - 1) + fib(n - 2); }; // Start async work process.nextTick(function(){ try{ const result = fib(data); self.emit('work-done', null, result); } catch(err){ self.emit('work-done', err); } }); } }; }; // Foo class using example const foo = new Foo(); foo.on('work-done', (err, result) => { if(err) console.log(err); else console.log('Result: ' + result); }); foo.doWork('jjjj'); // Error case console.log(); foo.doWork(43); // Success case console.log("Hello! Let's talk while I'm working."); console.log('How are you?'); console.log(); 

它工作没有问题。 我得到了结果:

 Error: Invalid data at Foo.doWork (C:\nodejs\index.js:13:27) at Object.<anonymous> (C:\nodejs\index.js:44:5) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at startup (bootstrap_node.js:149:9) Hello! Let's talk while I'm working. How are you? Result: 433494437 

现在我想在我的JavaScript代码中使用我的Foo类,这个代码将被web浏览器使用。 如何重写Foo类的这篇文章? 我在我的代码中做了哪些更改?