简体   繁体   English

NODEJS中的Javascript方法链接

[英]Javascript Method Chaining in NODEJS

When you chain a method in javascript, does it get called on the initial object? 当您在javascript中链接方法时,是否会在初始对象上调用它? Or the return object of the previous method? 还是先前方法的返回对象?

I am asking this because in Node I am chaining .listen() . 我问这个问题是因为在Node中我链接了.listen()

It works: 有用:

var http = require("http");

http.createServer(function (request, response) {
   response.writeHead(200, {
     'Content-Type': 'text/plain'
   });
   response.end('Hello World\n');
}).listen(8088);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

It doesn't work when listen() is called after createServer : createServer之后调用listen()时,它不起作用:

http.createServer(function (request, response) {
   response.writeHead(200, {
     'Content-Type': 'text/plain'
   });
   response.end('Hello World\n');
})

http.listen(8088);

It says that listen() is not function. 它说listen()不起作用。 Why does it work when I chain it then? 为什么当我链接它时它会起作用?

Because http is the module which is different from the instance of http.Server created by createServer. 因为http是与createServer创建的http.Server实例不同的模块。 See documentation here and try console.log() ing the variables to see what functions and properties are defined on them. 请参阅此处的文档并尝试使用console.log()变量,以查看在其上定义了哪些函数和属性。

Fluent interfaces work by returning the same object you called on (by ending the method with return this ) so you can chain calls on that object (hence, make it "fluent"). 流利的接口通过返回您所调用的同一对象来工作(通过以return this结束该方法),因此您可以链接对该对象的调用(因此,使其成为“流利的”)。

https://en.wikipedia.org/wiki/Fluent_interface https://en.wikipedia.org/wiki/Fluent_interface

In your case, its not a matter of method chaining. 就您而言,这与方法链接无关。 Calling http.createServer returns a new object different than http, which you can call listen on. 调用http.createServer返回一个不同于http的新对象,您可以在其上调用listen。

This is because createServer returns a new instance of http.Server . 这是因为createServer返回http.Server的新实例。

Class: http.Server

This class inherits from net.Server and has the Event 'listening' . 此类从net.Server继承,并且具有事件'listening' More information 更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM