Skip to content

20. 实现 Object.create

js
Object.create2 = function(proto, propertyObject = undefined) {
  if (typeof proto !== 'object' && typeof proto !== 'function') {
    throw new TypeError('Object prototype may only be an Object or null');
  }

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

  if (propertyObject !== undefined) {
    Object.defineProperties(obj, propertyObject);
  }

  if (proto === null) {
    obj.__proto__ = null;
  }

  return obj;
};