Object.creat-MDN
三步
1. 创建一个临时函数
2. 传入对象指向构造函数的原型
3. 返回临时函数的一个新实例
实现
/** * 创建一个已经选择了原型的新对象,但没有把第二个参数考虑在内 * @param {*} proto * @returns */function objectCreate(proto) { function F() {}; F.prototype = proto; return new F();}// function objectCreate(proto, protopertiesObject) {// let res = {};// res.__proto__ = proto;// Object.defineProperty(res, protopertiesObject);// return res;// }
测试
// caseconst person = { isHuman: false, age: 18};const me = objectCreate(person);// const me = Object.create(person);me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"me.age = 20;console.log(me)console.log(me.isHuman)console.log(person);// { name: 'Matthew', age: 20 }// false// { isHuman: false, age: 18 }