Object Chaining

Object Chaining

Object chaining is like fluent api make your code more readable. It also like extension method in other language etc. C#.

function Player(player_name) {
    this.name = player_name;
}

Player.prototype.attack = function (other_player, damage) {
    console.log(`${this.name} damaged ${other_player.name} by ${damage}`);
    return this;
};

// Must invoke with `new` if not prototype doesn't bind on it.
const player_one = new Player('PlayerOne');
const player_two = new Player('PlayerTwo');
player_one.attack(player_two, 2).attack(player_two, 3);
player_two.attack(player_one, 3).attack(player_one, 2);

// PlayerOne damaged PlayerTwo by 2
// PlayerOne damaged PlayerTwo by 3
// PlayerTwo damaged PlayerOne by 3
// PlayerTwo damaged PlayerOne by 2

Other situation

Sometime the object has their own prototype and if you edit or add another prototype function may break it, you can create your own and extend it.

function Player(name) {
    this.player_name = name;
    this.health = 0;
    this.str = 0;
    this.agi = 0;
    this.int = 0;
}

Player.prototype.logStats = function () {
    console.log(`PlayerName: ${this.player_name}`);
    console.log(`HP: ${this.health}`);
    console.log(`STR: ${this.str}`);
    console.log(`AGI: ${this.agi}`);
    console.log(`INT: ${this.int}`);
}

function PlayerAttribute(player) {    
    this.player = player;
}

PlayerAttribute.prototype.setHealth = function (health) {
    this.player.health = health;
    return this;
};

PlayerAttribute.prototype.setStrength = function (str) {
    this.player.str = str;
    return this;
};

PlayerAttribute.prototype.setAgility = function (agi) {
    this.player.agi = agi;
    return this;
};

PlayerAttribute.prototype.setIntelligence = function (int) {
    this.player.int = int;
    return this;
};

PlayerAttribute.prototype.done = function() {
    return this.player;
}

const player = new PlayerAttribute(new Player('player_one'))
    .setHealth(10)
    .setStrength(5)
    .setAgility(7)
    .setIntelligence(3)
    .done();