What is the difference between creating an object from the literal form or from a constructor function?

Asked

Viewed 185 times

5

I wonder if it has any difference or relevance between the two forms below in the construction of an object:

Create an object from the literal form:

let pessoa = {
   nome: 'Pedro'
};

console.log(pessoa.nome);

Create an object from a constructor function:

let pessoa = new Person();

function Person() {
    this.nome = 'Pedro';
}

console.log(pessoa.nome);

1 answer

5


In short, the difference is in the way objects are created and therefore the constructor of objects.


In your first example:

let pessoa = {
   nome: 'Pedro'
};

console.log(pessoa.nome);

You are simply creating a new object through its literal notation. You are assigning a property name directly through that notation. There is nothing very special beyond that.

In his second example:

function Person() {
    this.nome = 'Pedro';
}

let pessoa = new Person();
console.log(pessoa.nome);

You are instantiating a new constructor object Person, i.e., you are creating a new object of the "type" Person.

There is, then, the difference, since when you use the operator new, the returned object (instantiated) will inherit the prototype of its constructor function. In its example, one can notice the difference with the following example:

const person1 = {
  name: 'Luiz'
};

function Person() {
  this.name = 'Luiz';
}

const person2 = new Person();

console.log(person1.constructor.name); // "Object"
console.log(person2.constructor.name); // "Person"

So it can be concluded that basically the difference is this:

  • In its first example, how the object is being constructed using its notation literal, he will inherit the prototype from the builder Object (standard for literal objects).
  • In the second example, however, the manufacturer is used Person, a function created by the programmer himself. There’s the difference.

All this is very linked to the functioning of prototypes in Javascript. To learn more, read this other question.


By way of curiosity, if you want to create an object that has no inherited relative, you can use Object.create(null), the first argument being the prototype that the object to be created will inherit.

const example1 = {};
const example2 = Object.create(null);

console.log(example1.constructor.name); // "Object"
console.log(example2.constructor); // undefined

  • Now I was even more confused, I’m learning about OOJS and I don’t understand much about prototype, builder, inherit, polymorphism, etc I’ll give another study on these concepts, so when I review this answer will be clearer to me, thanks! :)

  • 1

    @felipecardozo On prototype, a good starting point is here: https://answall.com/q/15239/112052

  • @hkotsubo, thanks! for sharing the link of the reply I will give a read.

Browser other questions tagged

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