[JavaScript] Object.create vs prototype for Creating Objects

Tech Sharing 2019-02-25
[JavaScript] Object.create vs prototype for Creating Objects

Comparing Object.create() and prototype: the former creates a new object with a given prototype, the latter shares properties via the prototype chain — differing in inheritance and this binding.

Creating an object with Object.create()

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);
me.name = "Matthew";
me.isHuman = true;
me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

prototype

function person(){};

person.prototype.text = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = new person();
me.name = "Matthew";
me.isHuman = true;
me.text.printIntroduction();
// expected output: "My name is undefined. Am I human? false"