Object oriented Javascript: Different way to create Object with example

Hi Guys,

There are different ways to create Object in javascript. 
  1. Objects created with syntax constructs
  2. With a constructor
  3. With Object.create
  4. With the class keyword

1. Objects created with syntax constructs
var myApp = myApp || {};
console.log(typeof myApp);

var myArray = ["hello","!", "how","are", "your","?"];
console.log(typeof myArray);


2. With a constructor
A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.

function Vehicle(){
    this.name;
    this.type;
}

Vehicle.prototype = {
    addVehicle : function(name, type){
       this.name = name;
       this.type = type;
    }
}

var car = new Vehicle();
console.log(car);
console.log(typeof car);

3. With Object.create
ECMAScript 5 introduced a new method: Object.create(). Calling this method creates a new object. The prototype of this object is the first argument of the function
var parentObject = {
 name: "Shankar"
}; 

var childObject = Object.create(parentObject);
console.log(childObject.name);

4. With the class keyword
ECMAScript 6 introduced a new set of keywords implementing classes. Although these constructs look like those familiar to developers of class-based languages, they are not the same. JavaScript remains prototype-based. The new keywords include class,constructor, static, extends, and super.

"use strict";
  
class ParentClass{
 constructor(){
  console.log("parent class constuctor");
 }
}
  
class ChildClass extends ParentClass{
 get display(){
  console.log("child clss display");
 }
}

var childClass = new ChildClass();
childClass.display;
Good Day :)

Post a Comment

0 Comments