// Object.create方法,该方法可以创建一个对象,并让新对象的__proto__属性指向已经存在的对象。
const obj = Object.create(constructor.prototype)
// 等价于
const obj = {}
obj.__proto__ = constructor.prototype
思路:
非常简单,内部定义一个构造函数,把传入的对象直接作为这个构造函数的原型,最后再返回出去
function createObj(obj) {
function F() { }
F.prototype = obj
return new F()
}
// test
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = createObj(person);
console.log(me);
me.name = 'Matthew';
me.isHuman = true;
me.printIntroduction();