Last active
April 1, 2019 20:06
-
-
Save ositowang/24291f73821dfc3d4a7914e46012fc4b to your computer and use it in GitHub Desktop.
simulating the new operator in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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