如何模拟实现new效果

294 阅读1分钟

New Function 都做了哪些事情?

new 做了三件事

  1. 创建一个新对象
  2. 将构造函数的作用域赋给这个新对象
  3. 执行构造函数中的代码,为这个新对象添加属性、方法
  4. 返回新对象

需要实现的功能是,实例可以访问到私有属性,实例可以访问构造函数 constructor.prototype 原型上的属性方法,返回这个对象。需要注意如果构造函数本身返回了函数或者对象,那个返回这个函数或对象。

简单代码描述:

  let obj = {}
  obj.__proto__ = Base.prototype
  Base.call(obj)
  return obj

自己模拟实现new实现:

  function newFactory(ctor, ...args) {
    if (typeof ctor !== 'function') {
      throw 'the first params must be a function'
    }
    let obj = new Object()
    obj = Object.create(ctor.prototype) // 创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

    let res = ctor.apply(obj, [...args])
    // 当构造函数没有return时候,返回新建的对象
    // 有返回时返回函数的返回值
    let isObject = typeof res === 'object' && typeof res !== null
    let isFunction = typeof res === 'function'
    return isObject || isFunction ? res : obj
  }

  // 测试
  function Person(age, name) {
    this.age = age
    this.name = name
    this.getAge = function () {
      return this.age
    }
  }
  Person.prototype.getName = function () {
    return this.name
  }
  let person = newFactory(Person, 19, 'mike', 3)