05-类
9.4 类
JavaScript现在像它的兄长们一样支持类了。我们再也不需要绕一个大圈子来在JavaScript中模拟类的行为了。
在第3章中,我创建过一个类—— InputChecker
,用的是旧语法:
var util = require('util');
var eventEmitter = require('events').EventEmitter;
var fs = require('fs');
exports.InputChecker = InputChecker;
function InputChecker(name, file) {
this.name = name;
this.writeStream = fs.createWriteStream('./' + file + '.txt',
{'flags' : 'a',
'encoding' : 'utf8',
'mode' : 0666});
};
util.inherits(InputChecker,eventEmitter);
InputChecker.prototype.check = function check(input) {
var command = input.toString().trim().substr(0,3);
if (command == 'wr:') {
this.emit('write',input.substr(3,input.length));
} else if (command == 'en:') {
this.emit('end');
} else {
this.emit('echo',input);
}
};
我将代码略微进行了改动,将 check ()
函数内嵌到了对象的定义中。然后再使用ES6的类来实现 InputChecker
。在进行修改之前,需要启动严格模式,因为新的类功能必须使用严格模式。
在旧的实现中,我们不得不使用 util.inherits ()
方法来继承构造函数的父构造函数中的原型方法。相对而言,在新的实现中,我们的类会继承 EventEmitter
对象的方法。我添加了用来创建和初始化新对象的构造方法。在构造方法中,我使用 super ()
来调用父类中的函数。
'use strict';
const util = require('util');
const eventEmitter = require('events').EventEmitter;
const fs = require('fs');
class InputChecker extends eventEmitter {
constructor(name, file) {
super()
this.name = name;
this.writeStream = fs.createWriteStream('./' + file + '.txt',
{'flags' : 'a',
'encoding' : 'utf8',
'mode' : 0o666});
}
check (input) {
let command = input.toString().trim().substr(0,3);
if (command == 'wr:') {
this.emit('write',input.substr(3,input.length));
} else if (command == 'en:') {
this.emit('end');
} else {
this.emit('echo',input);
}
}
};
exports.InputChecker = InputChecker;
check()
方法并不是通过原型对象添加的,而是作为一个方法直接被加入类中的。我们定义时并没有用到 var
或者 function
关键字——只是定义了这个方法。但是,所有的逻辑都和之前一样,或者非常相似。
而应用中使用新版机密(双关语,classified原意是机密的,此处指的是使用class重新定义的类)模块的代码并没有任何修改:
var InputChecker = require('./class').InputChecker;
// testing new object and event handling
var ic = new InputChecker('Shelley','output');
ic.on('write', function (data) {
this.writeStream.write(data, 'utf8');
});
ic.addListener('echo', function( data) {
console.log(this.name + ' wrote ' + data);
});
ic.on('end', function() {
process.exit();
});
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(input) {
ic.check(input);
});
就像这段代码所展示的,我们不需要为了使用严格模式下定义的模块,而在代码中使用严格模式。
**Mozilla的万用文档** 如果遇到任何有关JavaScript的问题,Mozilla开发者网络都是我们查找资料的首选网站。对于新的类功能也不例外。他们为这个功能提供了非常好的文档。