4ways to create objects in javascript!
- Creating object with a constructor:
function vehicle(name,maker,engine){
this.name = name;
this.maker = maker;
this.engine = engine;
}
//new keyword to create an object
let car = new vehicle('GT','BMW','1998cc')
- Using object literals:
const obj = { }
- Creating object with Object.create() method:
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
const coder = {
isWorking : false,
myIntroduction : function(){
console.log(`Name is ${this.name}.Am I working?: ${this.isWorking}`);
}
};
const newObj = Object.create(coder);
newObj.name = 'Ruchika';
newObj.isWorking = true;
newObj.myIntroduction();
- Using es6 classes:
//using es6 classes
class City {
constructor(name, maker, engine) {
this.name = name;
this.place = maker;
}
}
let newObj = new City('Mumbai', 'juhu');
console.log(newObj.name); //Mumbai