How can JavaScript call a chain of methods?

Viewed 71

I recently got a question while looking at the javascript.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
}).listen(8080);

my question is this.

function().function();

How does this call a function consecutively? If I want to know more about this grammar, what keyword should I search for? Thank you.

2 Answers

The pattern you're looking for is Fluent interface. It can be implemented pretty easily with JavaScript like this:

const obj = {
    function1() {
        console.log('function1');
        return this;
    },
    
    function2() {
        console.log('function2');
        return this;
    }
}

obj.function1().function2().function1();

You could also use Promises in case of asynchronous functions like this:

const delay = fun => new Promise(resolve => setTimeout(() => [resolve, fun].forEach(x => x()), 1000));

const obj = {
    promise: Promise.resolve(),

    function1() {
        this.promise = this.promise.then(() => delay(() => console.log('function1')));
        return this;
    },
    
    function2() {
        this.promise = this.promise.then(() => delay(() => console.log('function2')));
        return this;
    }

}

obj.function1().function2().function1();

http.createServer function returns an object with property listen which is a function, the function is called immediatelly after object is created.

function getDog(dogName) {
    return {
        name: dogName,
        bark: function () {
            console.log("woof woof"); 
        }
    }
}

let dog1 = getDog("wolfie").bark();
// is the same as
let dog1 = getDog("wolfie");
dog1.bark();
Related