Object.creat-MDN

三步

1. 创建一个临时函数

2. 传入对象指向构造函数的原型

3. 返回临时函数的一个新实例

实现

  1. /**
  2. * 创建一个已经选择了原型的新对象,但没有把第二个参数考虑在内
  3. * @param {*} proto
  4. * @returns
  5. */
  6. function objectCreate(proto) {
  7. function F() {};
  8. F.prototype = proto;
  9. return new F();
  10. }
  11. // function objectCreate(proto, protopertiesObject) {
  12. // let res = {};
  13. // res.__proto__ = proto;
  14. // Object.defineProperty(res, protopertiesObject);
  15. // return res;
  16. // }

测试

  1. // case
  2. const person = {
  3. isHuman: false,
  4. age: 18
  5. };
  6. const me = objectCreate(person);
  7. // const me = Object.create(person);
  8. me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
  9. me.age = 20;
  10. console.log(me)
  11. console.log(me.isHuman)
  12. console.log(person);
  13. // { name: 'Matthew', age: 20 }
  14. // false
  15. // { isHuman: false, age: 18 }