Video : Four ways of creating an object in JavaScript

There are four ways an object can be created in JavaScript

  1. object as a literal
  2. Using the new operator, also knows as constructor invocation pattern
  3. Using the Object.create() method
  4. Using the class starting ES6

Watch full video here :

Source Code :

// Fours ways of creating an object in JavaScript
// 1. object as a literal
var car = {
model: 'bmw',
color: 'red',
price: 2000,
engine : {
type :'petrol',
power : 120
}
}
car.owner = 'foo';
Object.defineProperty(car, "yearmade", {
writable: true,
enumerable: true,
configurable: false,
value: 1984
});
console.log(JSON.stringify(car));
// 2. using the new operator a.k.s Constructor Invocation Pattern
function Car(model, color) {
this.model = model;
this.color = color;
Object.defineProperty(this, "yearmade", {
writable: true,
enumerable: true,
configurable: false,
value: 1984
});
}
console.log(Car.prototype);
var c1 = new Car('BMW','Red');
var c2 = new Car('Audi','Black');
console.log(c1.yearmade);
// 3 using the Object.create() method
//it allows you to create an object from an existing object
var Car1 = {
model: 'BMW',
color: 'red'
}
var ElectricCar = Object.create(Car1,{ym:{
writable: true,
enumerable: true,
configurable: false,
value: 1984
}});
//console.log(ElectricCar.ym); // BMW
// 4 using the class starting ES6
class Car3 {
constructor(maker, price) {
this.maker = maker;
this.price = price;
}
getInfo() {
console.log(this.maker + " costs : " + this.price);
}
}
var carobj1 = new Car3('BMW',2000);
carobj1.getInfo();

For more such learning videos, subscribe to  https://www.youtube.com/c/geek97

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s