MarsPen / blog

3 stars 0 forks source link

【手写篇 - Day 06】实现 `Object.create` #7

Open MarsPen opened 2 years ago

MarsPen commented 2 years ago

题目描述

Object.create()可以用来创建新的对象。

你能实现一个 myObjectCreate() 来实现(大概)相同的逻辑吗 ?

注意

MarsPen commented 2 years ago

思路

代码

function myObjectCreate(proto) {
  if (typeof proto !== 'object' && typeof proto !== 'function') {
    throw new TypeError("对象原型必须是一个对象或者函数")
  } else if (proto === null) {
    throw new TypeError("对象原型不能是 null")
  }

  function F() {}
  F.prototype = proto;
  return new F();
};

补充知识