I have been using Node since 0.11/0.12 so correct me if this is a matter of coming relatively late to the party.
I am trying to understand the difference between using util.inherits(Son, Dad)
and simply extending the prototype of Son.prototype = [new] Dad()
.
For this example I am subclassing a Transform stream using util.inherits
first:
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)
The above seems to be the most common way to go about this in Node. The following (extending the prototype) works just as well (seemingly), and it's simpler:
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)
For the record, I know there is through2
, which has a very simple interface, and do help reducing a few lines of code (see below), but I am trying to understand what is going under the hood, hence the question.
var thru = require("through2")(function (chunk, encoding, done) {
this.push(/* transform chunk! */)
done()
})
process.stdin.pipe(stream).pipe(process.stdout)
So, what are the differences between util.inherits
and extending the prototype in Node?