2021-08-12 手写new 实现

 function newFn(fn,...args) {
    let obj = Object.create(fn.prototype),
         //将obj的隐式原型指向fn的prototype
         result = fn.call(obj,...args)
         //为obj拷贝自身属性  
         if(result instanceof Object) {
                //result 在Object的原型链上,说明返回了对象或是数组
                return result
          }else {
                return obj
          }
}
//测试
function Person(name,age,sex) {
    this.name = name 
    this.age = age
    this.sex = sex
}
newFn(Person,'Ej',18,'feMale')

你可能感兴趣的:(2021-08-12 手写new 实现)