How to create an object with `Object.create()`?

// simple usage
let character = Object.create({});
character.name = 'Son Goku';

// output: { name: 'Son Goku' }
console.log(character);

// extended usage
// prototype object
const sayan = {
  hasTail: true,
  turnIntoSuperSayan() {
    console.log(`${this.name} turned into a super sayan!`);
  }
};

const character = Object.create(sayan);
character.name = 'Son Goku';
character.hasTail = false;

// output: "Son Goku turned into a super sayan!"
character.turnIntoSuperSayan();

// output: { name: 'Son Goku', hasTail: false }
console.log(character);
Copy

April 12th, 2020

# Object.create() - Create an object

Add to bookmarks

Object.create is a way to create an object by applying a prototype object as first parameter (can be an empty object as well).

The optional second parameter can be an object of properties which will be applied to the new object.

TL;DR: It's an alternative to new Object()

HomeBookmarks