1. // Object.create方法,该方法可以创建一个对象,并让新对象的__proto__属性指向已经存在的对象。
  2. const obj = Object.create(constructor.prototype)
  3. // 等价于
  4. const obj = {}
  5. obj.__proto__ = constructor.prototype

思路:

非常简单,内部定义一个构造函数,把传入的对象直接作为这个构造函数的原型,最后再返回出去

  1. function createObj(obj) {
  2. function F() { }
  3. F.prototype = obj
  4. return new F()
  5. }
  6. // test
  7. const person = {
  8. isHuman: false,
  9. printIntroduction: function () {
  10. console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  11. }
  12. };
  13. const me = createObj(person);
  14. console.log(me);
  15. me.name = 'Matthew';
  16. me.isHuman = true;
  17. me.printIntroduction();

image.png