简体   繁体   中英

Javascript Method Chaining in NODEJS

When you chain a method in javascript, does it get called on the initial object? Or the return object of the previous method?

I am asking this because in Node I am chaining .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 :

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. 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. See documentation here and try console.log() ing the variables to see what functions and properties are defined on them.

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").

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.

This is because createServer returns a new instance of http.Server .

Class: http.Server

This class inherits from net.Server and has the Event 'listening' . More information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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