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

Example:

function Wechat() {
  this.name = 'fedaily'
}
Wechat.prototype.getName = function() {
  return this.name
}

const wechat = new Wechat()
// wechat.name === fedaily
// wechat.getName() === fedaily
Copy the code

As you can see, the instance has access to properties of the constructor as well as properties on the prototype object.

So we can simulate:

function newFactory() {
  var obj = new Object(),
  Constructor = [].shift.call(arguments);
  obj.__proto__ = Constructor.prototype;
  // Handle the case where the constructor returns a value
  // Return value if it is an object, obj otherwise
  var ret = Constructor.apply(obj, arguments);
  return typeof ret === 'object' ? ret : obj;
};
Copy the code