Question:
I'm having a technical question in JavaScript:
- What is the difference between
Object.create
andnew Object()
? - What cases do I have to adopt one over the other?
Answer:
The Object.create
method takes parameters. The first is mandatory and will be used as a prototype of the new object. The second is a map of properties with which an object is already "born".
new Object()
is a longer, non-recommended way of saying {}
.
The three lines of code below are equivalent:
let a = {}; // legal
let b = new Object(); // coisa de dinossauros pedantes
let c = Object.create(null); // isso pode ser útil se ao invés de nulo
//você passar um parâmetro.
The create
method can be very useful if you use some more complex logic to create your objects. Again, the two code snippets below are equivalent:
// forma verbosa
let foo = {};
foo.prototype = Array;
let bar = {nome: "john", idade: 21};
for (let propriedade in bar) {
foo[propriedade] = bar[propriedade];
}
// forma curta
let foo = Object.create(Array, {nome: "john", idade: 21});