4
Let’s say we want to create an object called Retângulo
(if desired, with properties such as length, width, perimeter and area). As shown in the next diagram (created based on the information present at this link), we can create objects using at least two different ways
- Object initializers (Object initializers)
- Constructor functions (Constructor functions)
So within object initializers, there are at least three different ways to create.
I understand that, at first glance, the use of the constructor function will require writing the function and only then initializing it. Something like
function Rectangle(a, b) {
this.length = a;
this.width = b;
this.perimeter = 2 * (a+b);
this.area = a * b;
}
and then use
const rec = new Rectangle(a, b);
Although it may seem like extra work, when do we want to use the constructor functions? Also, it is irrelevant if we initialize with the new Rectangle()
, Rectangle.create()
or var Rectangle = {}
?
Do any of these answers answer your question? Difference between constructor and function that returns literal object or What is the difference between creating an object from the literal form or from a constructor function?
– Luiz Felipe
I’d say no @Luizfelipe
– Tiago Martins Peres 李大仁