Matthew Morris
Matthew Morris

Reputation: 333

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?

Upvotes: 0

Views: 551

Answers (3)

Jason Livesay
Jason Livesay

Reputation: 6377

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.

Upvotes: 2

JavierIEH
JavierIEH

Reputation: 741

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.

Upvotes: 0

Gaurav joshi
Gaurav joshi

Reputation: 1799

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

Upvotes: 0

Related Questions