Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code shows four ways of creating an object in JavaScript
// 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.