js new操作符原理

130 阅读1分钟
 function test(name, age) {
      this.name = name
      this.age = age
    }
    
    function myNew() {
      let constructor = Array.prototype.shift.call(arguments)
      if (typeof constructor !== 'function') {
        console.error('类型错误')
        return
      }
      // 使函数的原型对象是新对象的原型
      let newObject = Object.create(constructor.prototype)
      // 修改函数的this指向
      let res = constructor.apply(newObject, arguments)
      // 判读res类型
      let flag = res && (typeof res == 'object' || typeof res == "function")
      // 如果函数有返回值并且类型为object或function,返回res,否则返回新对象
      return flag ? res : newObject

    }
    console.log(myNew(test, '张三', '22'));
    //test {name: '张三', age: '22'}