Implementation of new

Time:2022-6-20

What new did:

  1. Create an object
  2. Point this in the function to this object
  3. Executing methods within functions
  4. Return this object

Note:

  1. Create an object that inherits the properties and methods of the function prototype
  2. If the function does not return an object type, the object created in the first step will be returned
function myNew(Fn, ...args) {
 //Create an object (and inherit fn.prototype)
 var obj = Object(Fn.prototype)
 //Call FN with obj
 var resault = Fn.apply(obj, args)
 //Back
 var type = typeof resault
 var isObj = resault != null && (type === 'object' || type  ==='function')
 return isObj ? resault : obj
}