+ 4
Why is there so many ways of creating objects in javascript, and which one should i follow?
6 Antworten
+ 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...
+ 11
Yup, Victor is spot on!
+ 9
It's a pleasure Sun Lun!
+ 5
Since ES6 classes is your favorite then use it. Just use a transpiler like babel for backward compatibility.
+ 4
Very helpful...tq
+ 2
What makes the second form better than the last form?