Open chenfan0 opened 2 years ago
判断函数本身的返回值是否为函数或者对象类型,如果函数本身返回的就是一个对象类型,那么直接返回函数本身返回的对象。如果函数本身返回的是一个基本数据类型,那么就返回一开始创建出来的对象
function myNew(fn, ...args) { // 判断传递的参数是否合法 if (typeof fn !== 'function') { throw new Error('传递的参数不能被new'); } // 创建一个空对象,并且将该对象的__proto__属性指向fn.prototype const obj = Object.create(fn.prototype) // 执行函数体,并将this指向创建出来的对象 const fnResult = fn.apply(obj, args) // 判断函数本身返回值是否为函数或者对象类型 if (typeof fnResult === 'object' || typeof fnResult === 'function') { return fnResult } return obj }
new操作时做了什么?
判断函数本身的返回值是否为函数或者对象类型,如果函数本身返回的就是一个对象类型,那么直接返回函数本身返回的对象。如果函数本身返回的是一个基本数据类型,那么就返回一开始创建出来的对象
代码实现