我正在研究 NodeJS Stream 代码和此示例 Streams article :
const { Readable } = require('stream');
const inStream = new Readable({
read() {}
});
inStream.push('ABCDEFGHIJKLM');
inStream.push('NOPQRSTUVWXYZ');
inStream.push(null); // No more data
inStream.pipe(process.stdout);
当我进入 new Readable()
调用时,我看到如下所示的代码:
const Stream = require('stream');
function Readable(options) {
// ...
Stream.call(this);
}
Stream.call(this)
是做什么的?我以前没有见过这样的代码。
我知道 Javascript Object.call() 方法的作用,并且通常在另一个函数中见过它。
myObj.myFunc.call(this);
我阅读了 MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call示例代码将两个对象组合在一起。
所以我相信调用 Stream.call(this)
后的 Readable
对象拥有所有 Stream 函数和字段值。
这是正确的吗?
我猜测这就是 Javascript 执行类似继承功能的方式,但没有继承。我认为这实际上相当于合并多个 Javascript 对象。
所以为了证明我的理解,我写了一个JSFiddle code example它显示了三个函数 fun1、fun2 和 fun3,并让 MyMultiObj 调用它们,如下所示:
function MyMultiObj() {
fun1.call(this);
fun2.call(this);
fun3.call(this);
}
let myMulti = new MyMultiObj();
在此代码中,myMulti
对象具有 4 个函数 MyMultiObj、fun1、fun2 和 fun3 的所有功能和字段。
我还注意到通过原型(prototype)定义的函数(例如,fun2.prototype.really2()
没有合并/可用,这是有道理的,因为这种方法不使用原型(prototype))。
我认为这很酷,并且可以看到好处,但想要
(a) 验证我的理解是否正确,...调用
Stream.call(this)
后的Readable
对象具有所有 Stream 函数和字段值,以及(b) 找出为什么这样做而不是典型的原型(prototype)设计/继承(如果有原因)。
最佳答案
使用call()
只是执行一个函数,this
是传递给它的对象,在构造函数内部它就像一个super()
用其他语言(和 ES6)调用:
function Stream() {
this.something = 1;
}
function Readable () {
Stream.call(this);
}
(new Readable()).something // 1
等于:
class Stream {
constructor() {
this.something = 1;
}
}
class Stream extends Readable {
constructor() {
super(); // <<
}
}
So my belief is that the Readable object after calling Stream.call(this) has all of the Stream functions and field values.
仅限直接在构造函数中设置的内容。它没有原型(prototype)的值/方法
关于javascript - 将多个 Javascript 对象合并为一个。 Stream.call(this) 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036208/