/java-script/

Fluent Interfaces In JavaScript

2014-08-15 01:38:20

collection.js

function Collection() {

    var arr = [];

    var add = function (item) {
        arr.push(item);
        return this;
    };

    var get = function () {
        return arr;
    };

    return {
        add: add,
        get: get
    }
}

var col =
    new Collection()
        .add({name:'Lorem'})
        .add({name:'Ipsum'})
    ;
console.log(col.get());

builder.js

function Configuration() {

    var setProtocol = function (protocol) {
        this.protocol = protocol;
        return this;
    };

    var setServer = function (server) {
        this.server = server;
        return this;
    };

    var setPort = function (port) {
        this.port = port;
        return this;
    };

    var getConf = function () {
        return {
            protocol: this.protocol,
            server: this.server,
            port: this.port
        }
    };

    return {
        withProtocol: setProtocol,
        withServer: setServer,
        withPort: setPort,
        getConf: getConf
    }
}

var config =
    new Configuration()
        .withProtocol("http")
        .withServer("btbw.pl")
        .withPort(22)
    ;

console.log(config.getConf());