Skip to content

Instantly share code, notes, and snippets.

@debugmodedotnet
Created August 1, 2019 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debugmodedotnet/f3608fb337a809e2139a9e8c4a5eb8c6 to your computer and use it in GitHub Desktop.
Save debugmodedotnet/f3608fb337a809e2139a9e8c4a5eb8c6 to your computer and use it in GitHub Desktop.
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