Object.create or new Object () in JavaScript? What's the difference between the two?


I'm going through a technical question in JavaScript: What is the difference between Object.create and new Object() ? Which cases do I have to adopt one instead of the other?

asked by anonymous 28.08.2014 / 21:36

1 answer


The method Object.create receives parameters. The first is required and will be used as prototype of the new object . The second is a property map with which the object is already "born."

new Object() is a longer, non-recommended way to say {} .

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});
28.08.2014 / 22:06