在 NodeJS 中实现接口

Implementing Interfaces in NodeJS

NodeJS 文档指出:

"The request object is an instance of IncomingMessage. The request object that's passed in to a handler implements the ReadableStream interface"

"So far we haven't touched on the response object at all, which is an instance of ServerResponse, which is a WritableStream."

JS 有原型继承,所以当文档说它是一个 instance 它意味着它添加到原型链,但是它是如何 在 JS 中实现接口?

这一切是如何联系起来的,又是如何运作的。 官方NodeJS文档没有解释。

来源 - Anatomy of an HTTP Transaction

编辑 - 我的问题与 JS 中的多重继承无关。它是关于 NodeJS 模块如何实现 JS 本身不支持的接口。如果我的问题有任何错误或我的知识不足,请原谅。谢谢!

接口 = 义务。

实现接口 = 提供调用您的人所期望的成员。

文档对这个特定界面的看法,ReadableStream?

嗯,here它说

All Readable streams implement the interface defined by the stream.Readable class

什么是stream.Readable

嗯,here提供了一个完整的"interface",由多个成员组成,包括readpipe

从技术上讲,在 JS 中有多种方式 "implementing" 这种义务:

  • 一个简单的方法是在一个应该实现该接口的对象的原型链中设置一个已经实现该接口的对象。这样所有接口成员都被委托(通过原型链)给另一个对象

  • 更直接的方法是直接由应该实现接口的对象提供所有必要的成员

  • 一种混合方法,其中一些成员委托给原型链,一些成员直接实现,一些成员通过直接调用委托给其他对象

由于语言的性质,期望实现接口的调用者将接受所有这些可能性。

例如文档说 接口 包含一个方法

foo(n)
where n is a number 
returns a number

您有以下选项。

方案一,直接实现

var o = {
    foo: function(n) {
       return 0;
    }
}

选项 2,沿原链委托

// an object that already implements the interface
// i.e. has function foo(n)
var existing = ....; 

var o = Object.create(existing);

// o has function foo though its proto

选项 3,通过调用委托

// an object that already implements the interface
// i.e. has function foo(n)
var existing = ....; 

var o = {
   foo: function(n) {
       return existing(n);
   }
}

所有这些选项也可以用构造函数表示。