当按以下方式调用诸如类中的createServer()
之类的方法时:
const http = require("http");
const server = http.createServer();
server.listen(3000);
到底发生了什么?如果我正确理解这一点,则http
类是一个构造函数,并且require函数实例化const http
。 createServer()
是构造函数http
的方法,该构造函数依次由http.createServer()
调用。 Node.js文档显示createServer()
“返回http.Server的新实例”。
这是否意味着createServer()
也可以作为构造函数并在已创建的实例中创建另一个实例?奇怪的是,server.__proto__
指向函数setTimeOut
,而不是createServer
或http
。
答案 0 :(得分:3)
containerRegistry.GetContainer()
是require()
,在这里用function
String
调用。
然后,Node.js查找"http"
模块,对其进行解释,然后http
返回带有给定模块导出内容的require()
。因此,一个模块是Object
d,它可以require()
多个事物,而不仅仅是export
。
JavaScript中的class
在其他语言中称为'字典'或'map',将值与类型为{{ 1}}。 (Object
后来被添加到JavaScript中,可以具有任何类型的键。)
String
只是此Map
中的createServer()
,在键function
下。调用时,它将返回另一个Object
,即"createServer"
的 instance 。它可以称为 工厂功能 。请参见其实现here。
Object
类似于class http.Server
中的listen()
,换句话说,是function
的方法。
这些都不是构造函数,它们是通过Object
关键字来调用的,例如:class http.Server
。
new
答案 1 :(得分:2)
需要一个班时到底发生了什么?
首先, http
只是一个模块而不是一个类。因此,如果您问调用require()
时发生了什么,它将返回参考导出的模块,例如http
。
在另一个方法中调用一个方法会发生什么情况?
这取决于方法的行为。就您而言,http.createServer()
返回http.Server
的实例。 这并不意味着http.createServer()
是http.Server
的构造函数,而是返回它的一个实例。
const http = require('http');
console.log(http.createServer() instanceof http.Server)
// true