javascript - 将多个 Javascript 对象合并为一个。 Stream.call(this) 是做什么的?

标签 javascript node.js node-streams

我正在研究 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/

相关文章:

node.js - 如何在可读的http流上运行Sharp转换并写入文件

javascript - 函数内的 Jquery bind()/live()

javascript - 使用 token 从 REST API 获取 JSON 的最佳方法

node.js - 在 i18next 中转义特殊字符

javascript - Eslint 未定义导入问题

javascript - 如何克隆 NodeJS 流?

node.js - Gulp 插件的条件设置取决于源文件

php - 将 php 变量值传递给 javascript

javascript - 从 Angular Ui-Router 中的参数定义 'parent' 值

javascript - TypeScript 将类型保存为未定义