Jor*_*ran 5 javascript inheritance stream node.js
我一直在使用Node自0.11/0.12,所以如果这是一个相对迟到的问题,请纠正我.
我试图理解使用util.inherits(Son, Dad)和简单扩展原型之间的区别Son.prototype = [new] Dad().
对于此示例,我首先使用第一个子类化Transform流util.inherits:
var util = require('util')
var Transform = require('stream').Transform
util.inherits(TStream, Transform)
function TStream () {
Transform.call(this)
}
TStream.prototype._transform = function(chunk, encoding, done) {
this.push(/* transform chunk! */)
done()
}
process.stdin.pipe(new TStream()).pipe(process.stdout)
Run Code Online (Sandbox Code Playgroud)
以上似乎是Node中最常见的解决方法.以下(扩展原型)同样有效(看似),而且更简单:
function TStream() {}
TStream.prototype = require("stream").Transform()
TStream.prototype._transform = function (chunk, encoding, done) {
this.push(/* transform chunk! */)
done()
}
process.stdin.pipe(new TStream()).pipe(process.stdout)
Run Code Online (Sandbox Code Playgroud)
为了记录,我知道有through2一个非常简单的界面,并帮助减少几行代码(见下文),但我试图了解底层的内容,因此问题.
var thru = require("through2")(function (chunk, encoding, done) {
this.push(/* transform chunk! */)
done()
})
process.stdin.pipe(stream).pipe(process.stdout)
Run Code Online (Sandbox Code Playgroud)
那么,util.inherits在Node中扩展原型之间有什么区别?
如果这是util.inherits的实现,则仅为您执行以下操作:
Child.super_ = Parent;
//set prototype using Object.create
Child.prototype = Object.create(Parent.prototype, {
constructor: {//repair the prototype.constructor
value: Child,
enumerable: false,
writable: true,
configurable: true
}
Run Code Online (Sandbox Code Playgroud)
这在Node.js中不是问题,但是在不支持Object.create的第二个参数的浏览器中(因为polyfil不允许它),您可以通过以下方式修复构造函数:
Child.prototype = Object.create(Parent.prototype);//if you polyfilled Object.create
//Child.prototype.constructor is now Parent so we should repair it
Child.prototype.constructor = Child;
Run Code Online (Sandbox Code Playgroud)
它要做的额外事情是设置Child.super_,因此在Child中,您可以执行以下操作:
function Child(){
Child.super_.call(this);//re use parent constructor
//same as Parent.call(this);
}
Run Code Online (Sandbox Code Playgroud)
有关原型和构造函数的更多信息,您可以阅读此答案。
根据以下说明,您将Transform错误地归为子类:
在扩展Transform类的类中,请确保调用构造函数,以便可以正确初始化缓冲设置。
因此,正确的代码应该调用它的构造函数(您不是用new调用Transform,而是构造函数可以处理错误的调用)。
var Transform = require("stream").Transform;
function TStream() {
Transform.call(this);//you did not do that in your second example
}
//your code sets prototype to an INSTANCE of Transform
// and forgets to call the constructor with new
//TStream.prototype = require("stream").Transform()
TStream.prototype = Object.create(Transform.prototype);
TStream.prototype.constructor = TStream;
TStream.prototype._transform = function (chunk, encoding, done) {
this.push(/* transform chunk! */)
done()
}
process.stdin.pipe(new TStream()).pipe(process.stdout)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3620 次 |
| 最近记录: |