Hi Guys,
There are different ways to create Object in javascript.
- Objects created with syntax constructs
- With a constructor
- With Object.create
- 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 :)
0 Comments