0

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?

1
  • 2
    It gets called on the return value Commented Nov 7, 2016 at 4:05

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.