Creation of objects in Javascript

Asked

Viewed 76 times

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

  1. Object initializers (Object initializers)
  2. Constructor functions (Constructor functions)

Criar objetos em JavaScript

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 = {}?

1 answer

4


There is a huge difference between the 3.

When you create the object through the constructor it is called and it is that code that will create the object as it was written. You might want to learn more about What good is a builder?.

The second calls a standard function that every JS object has, which is the function create(). It functions as a kind of constructor when there is no or does not use the constructor written specifically for a type of object. He makes the best effort to create an object of that kind that makes sense. Some object properties can be initialized with the values already stated in the prototype definition of the object.

The third form even has information that object is creating, only that it is creating an object and it will be essentially empty (it has what every object already has in JS). You can add members inside it after or even completely change that object. In fact, at least in the code shown, is creating a vailable called Rectangle that has nothing to do with the object you want to define.

Most often the constructor is the most correct form, especially if it exists it would become almost mandatory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.