There are four ways an object can be created in JavaScript
- object as a literal
- Using the new operator, also knows as constructor invocation pattern
- Using the Object.create() method
- Using the class starting ES6
Watch full video here :
Source Code :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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