Skip to content

Instantly share code, notes, and snippets.

@ositowang
Last active April 1, 2019 20:06
Show Gist options
  • Save ositowang/24291f73821dfc3d4a7914e46012fc4b to your computer and use it in GitHub Desktop.
Save ositowang/24291f73821dfc3d4a7914e46012fc4b to your computer and use it in GitHub Desktop.
simulating the new operator in javascript
const objectContructor = (...args) => {
//get the constructor function
let constructor = [].shift.call(args);
/**
* create a new object and link the prototype to the function prototype
* equals to var obj = new Object(), obj.__proto__ = Constructor.prototype
*/
let obj = Object.create(constructor.prototype);
// change the this bindings to the newly created objects
constructor.apply(obj, args);
// return the newly created object
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment