[JavaScript] Object.create 与 prototype 创建对象的区别

技术分享 2019-02-25
[JavaScript] Object.create 与 prototype 创建对象的区别

对比 Object.create() 与 prototype 两种创建对象方式:前者以指定对象为原型创建新对象,后者通过原型链共享属性,二者在属性继承与 this 指向上表现不同。

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"