JavaScript Object Creation Methods

Questions:

  • What are some different styles of object-oriented JavaScript? Is it possible to delineate?
  • What differentiates object creation methods?
    • myFun = New myObj()
      • MDN New Operator

        The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

    • Object.create()
      • MDN Object.Create

        The Object.create() method creates a new object, using an existing object to provide the newly created object’s __proto__ . (see browser console for visual evidence.)

 

var cardboardBox = new BoxConstructor(details)

    1. Creates a new object
      {} //<3
    2. Sets prototype of cardboardBox to prototype of BoxConstructor
      aThing.prototype = Something
    3. Call BoxConstructor with this = cardboardBox
      BoxConstructor.apply(cardboardBox, arguments)
    4. Return the object created

All together now!

function makeNew(constructor){
  var obj = {}
  Object.setPrototypeOf(obj, constructor.prototype)
  var argsArray = Array.from(arguments)//es6
//var argsArray = Array.prototype.slice.apply(arguments)//es5
  constructor.apply(obj, argsArray.slice(1))
  return obj
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *