Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8.实现object.create #10

Open
webVueBlog opened this issue May 23, 2022 · 0 comments
Open

8.实现object.create #10

webVueBlog opened this issue May 23, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant