Skip to content

JS objects

change the default prototype of an object

const objProto = {
    fullName: function () {
        return this.firstName + " " + this.lastName;
    },
};

const obj1 = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
};

Object.setPrototypeOf(obj1, objProto);

console.log(obj1.fullName()); // John Doe

Method chaining of objects

  • first method: without chaining
const student = {
    firstName: "John",
    lastName: "Doe",
    scores: [],
    average: 0,
    total: 0,
    addScore: function (score) {
        this.scores.push(score);
    },
    calculateAverage: function () {
        this.calculateTotal();
        this.average = this.total / this.scores.length;
    },
    calculateTotal: function () {
        this.total = 0;
        for (let i = 0; i < this.scores.length; i++) {
            this.total += this.scores[i];
        }
    },
};

student.addScore(10);
student.addScore(20);
student.addScore(30);
student.calculateAverage();
student.calculateTotal();
console.log(student.average); // 20
console.log(student.total); // 60
  • second method: with chaining
const student = {
    firstName: "John",
    lastName: "Doe",
    scores: [],
    average: 0,
    total: 0,
    addScore: function (score) {
        this.scores.push(score);
        return this; // will return the object itself, making the chaining possible
    },
    calculateAverage: function () {
        this.calculateTotal();
        this.average = this.total / this.scores.length;
        return this;
    },
    calculateTotal: function () {
        this.total = 0;
        for (let i = 0; i < this.scores.length; i++) {
            this.total += this.scores[i];
        }
        return this;
    },
    print: function () {
        console.log(this.firstName + " " + this.lastName + "  average: " + this.average + " total: " + this.total);
    },
};

student.addScore(10).addScore(20).addScore(30).calculateAverage().calculateTotal().print();
console.log({ student });