+ 4

Why is there so many ways of creating objects in javascript, and which one should i follow?

22nd Apr 2019, 7:41 AM
Sun Lun
Sun Lun - avatar
6 Answers
+ 16
There are three main ways of creating objects: - Object Literals - Constructor functions - ES2015 Classes --- Object Literals var O = { a: 1, b: 2 } These are used for very basic objects and for quick use. They don't need to have the new keyword before them as the object is created for a single variable. --- Constructor functions functions O() { this.a = 1; this.b = 2; } var Obj = new O(); These are one of the most common forms of make objects. Many browsers support this form. Using this form, we can create multiple objects. --- ES6 classes class O { constructor() { this.a = 1; this.b = 2; } } var Obj = new O() This is one of my most favourite forms of making objects. It is new and IE does not support it...
22nd Apr 2019, 8:40 AM
Edwin Pratt
Edwin Pratt - avatar
+ 11
Yup, Victor is spot on!
22nd Apr 2019, 2:59 PM
Edwin Pratt
Edwin Pratt - avatar
+ 9
It's a pleasure Sun Lun!
22nd Apr 2019, 8:45 AM
Edwin Pratt
Edwin Pratt - avatar
+ 5
Since ES6 classes is your favorite then use it. Just use a transpiler like babel for backward compatibility.
22nd Apr 2019, 2:25 PM
Victor Mbamara
Victor Mbamara - avatar
+ 4
Very helpful...tq
22nd Apr 2019, 8:42 AM
Sun Lun
Sun Lun - avatar
+ 2
What makes the second form better than the last form?
1st May 2019, 6:15 PM
Gabi Garcia
Gabi Garcia - avatar