new

role

The new operator creates an instance of a user-defined object type or of a built-in object with a constructor.

implementation

The four steps of new:

  1. Create a new object
  2. Link to the constructor prototype
  3. Binding this
  4. Return a new object
// Define a function where the first argument is a constructor and the other arguments pass... Args into arGS
function myNew (fun, ... args) {
  // Go to Step 1
  var obj = {}
  // Go to Step 2
  // By pointing obj.__proto__ to the prototype of constructor fun, obj can access the properties on the constructor prototype
  obj.__proto__ = fun.prototype
  // Corresponding to step 3, bind thi with apply
  var res = fun.apply(obj, args)
  // Go to Step 4
  // Return a new object. This checks whether res is object to ensure that the returned object is an object
  return res instanceof Object ? res : obj
}
Copy the code

Note: About the implementation of apply here apply, call, bind principle and implementation

Object.create()

role

Object.create() creates a new Object and uses the existing Object to provide the __proto__ of the newly created Object.

implementation

Object.create() takes two arguments: Proto (required) and propertiesObject (optional), where Proto is the prototype Object of the newly created Object, and propertiesObject is an Object that describes the properties of the new Object. Its description fields are shown below:

function myCreate (proto, propertiesObject) {
  // Determine if proto is object or function, and raise TypeError if it is not
  if (typeofproto ! = ='object' && typeofproto ! = ='function') {
    throw new TypeError('Object prototype may only be an Object or null')}// An error is reported if the propertiesObject is null
  if (propertiesObject === null) {
    throw new TypeError('Cannot convert undefined or null to object')}else {
    // Create an empty object and prototype it into the passed argument one
    var obj = {}
    obj.__proto__ = proto
    // Do not execute if propertiesObject is undefined
    if(propertiesObject ! = =undefined) {
      // Use object.defineProperties () to add attributes to the new Object
      Object.defineProperties(obj, propertiesObject)
    }
    return obj
  }
}
Copy the code

Note: TypeError is raised if the propertiesObject passed in is null or a non-original wrapper object.

Non-original wrapper object: similar to new String(‘111’)

A small problem

How is the Object created by New Object() different from object.create (null)?

New Object() creates objects with __proto__ attributes, while object.create (null) creates objects with no attributes