Javascript Object – ES5+

Published by

on

Javascript is being updated at a rapid pace over the years and here are some of the new features that I came across ( ES5 + onwards ).

Object.defineProperty( )

This method allows a precise addition to or modification of a property on an object.


//Sample code to show defineProperty()
var task = {
  title: " Task1",
  description: " Get some eggs"
};

Object.defineProperty(task, "toString", {
  value: function() {
    return this.title + ":" + this.description;
  },
  // allow task.toString = "something" ?
  writable: true,
  // console.log(task); //should show toString Method ?
  enumerable: true,
  // task.writable = false // Can user change it ?
  configurable: true
});

console.log(task.toString());

Object.create( )

A little refresher before we understand create() .

function Cricketer(name, skill) {
    this.name = name;
    this.skill = skill;
    this.isRetired = true;
}

Cricketer.prototype.showSkill = function () {
    console.log(this.skill + "!");
};

var sachin = new Cricketer("Sachin Tendulkar", "Batting");

// Outputs: "Batting!"
sachin.showSkill();

In the above code snippet , The Cricketer constructor contains initialisation logic, while Cricketer.prototype contains the methods that are shared across all Cricketer instances.

Implementing the same using Create() would look something like this

var Cricketer = {
    showSkill: function () {
        console.log(this.skill + "!");
    }
};

var sachin = Object.create(Cricketer, {
    name: { value: "Sachin Tendulkar" },
    skill: { value: "Batting" }
});

// Outputs: "laser beam!"
sachin.showSkill();

Now, what if we want to create a new type which inherits from Cricketer while adding its own functionality? What would that look like?

var genXCricketer = Object.create(Cricketer, {
    country: { value: "India" },
    saveTheMatch: {
        value: function () {
            console.log(this.name + " saved the day!");
        }
    }
});

var virat = Object.create(genXCricketer, {
    name: { value: "Virat Kohli" },
    skill: { value: "Batting" }
});

// Outputs: "Virat Kohli saved the day!"
virat.saveTheMatch();

Using Object.create makes setting up inheritance chains simple because any object can be used as a prototype. However, inheritance managed by Object.create can’t be detected by instanceof. Instead you’ll need to use the isPrototypeOf method, like so:

// Outputs: true
console.log(genXCricketer.isPrototypeOf(virat));

// Outputs: true
console.log(Cricketer.isPrototypeOf(virat)); <span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>

Because both superHero and superHuman are part of marvel’s prototype chain, their isPrototypeOf calls each return true.