There is no difference in relation to building object, but the semantics of how properties are added is different.
Literal objects in Javascript are syntactic sugar for building objects Object
.
Therefore, do:
const obj = new Object();
It’s exactly the same as this:
const obj = {};
In this sense, the difference is merely syntactic. And of course, you can already define properties directly in literal notation.
However, there is a difference when adding properties to the object (although this rarely makes a significant difference).
When adding the properties directly to the literal object, the same semantics of the function is used Object.defineProperty
- that is, semantics of definition of properties. When defining a property, no Setter will be activated.
Behold:
// Modificarei o protótipo para demonstrar que nenhum setter é invocado.
Object.defineProperty(Object.prototype, 'foo', {
set: function(val) {
console.log(`Called setter 'foo' with value '${val}'.`);
}
});
const myObj = {
foo: 'Bar' // Nenhuma mensagem será impressa ao se definir esta propriedade.
};
However, when using the allocation operator (=
), the semantics of assignment active the setters, if they exist. See:
// Modificarei o protótipo para demonstrar que o setter é invocado
Object.defineProperty(Object.prototype, 'foo', {
set: function(val) {
console.log(`Called setter 'foo' with value '${val}'.`);
}
});
const myObj = {};
myObj.foo = 'Bar'; // Uma mensagem será impressa ao se setar esta propriedade.
But note that at this point, the difference is no longer about the literal form or new Object
. The difference, in this sense, is the way the properties are added.
In short, in Javascript, the semantics of defining properties is different from the semantics of assigning properties.
Yes, but in the second way, in the manufacturing key you are assigned an array instead of a string. recommend using the second form, it is more succinct, although there is no why not do in the first way
– MarceloBoni