Skip to content

8.实现object.create #10

Open
Open
@webVueBlog

Description

@webVueBlog
Object.create = function(o) {
 function f() {};
 f.prototype = o;
 return new f;
}

Object.create() 方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

const _create = (proto, propertiesObject, isNeedSupportSecondParam = false) => {
  //参数校验
  if (typeof proto !== "object" && proto !== null)
    throw new Error("the first param must be an object or null");

  if (isNeedSupportSecondParam && propertiesObject === null) {
    throw "TypeError";
  }

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

  if (isNeedSupportSecondParam && propertiesObject !== null) {
    Object.defineProperties(obj, propertiesObject);
  }

  return obj;
};

Object.create(proto,[propertiesObject])

proto:新创建对象的原型对象。

propertiesObject:可选。需要传入一个对象,该对象的属性类型参照Object.defineProperties()的第二个参数。如果该参数被指定且不为 undefined,该传入对象的自有可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)将为新创建的对象添加指定的属性值和对应的属性描述符。

Object.mycreate = function(proto,propertiesObject){
    if(typeof(proto) !== 'object' && proto !== null) throw new Error("the first param must be an object or null");
    function Fn(){}
    Fn.prototype = proto
    if (propertiesObject) Object.defineProperties(obj, propertiesObject);
    return new Fn
}
const create = (prop, props) => {
  if (!['object', 'function'].includes(typeof prop)) {
    throw new TypeError(
      `Object prototype my only be an Object or null: ${prop}`
    )
  }

  const Ctor = function () {} // 创建构造函数

  Ctor.prototype = prop // 赋值原型

  const obj = new Ctor() // 创建实例

  if (props) Object.defineProperties(obj, props) // 支持第二个参数

  if (prop === null) obj.__proto__ = null // 支持空原型

  return obj
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions