Created
June 1, 2020 13:19
-
-
Save sunderls/90ee0c310530063752471c5337e77cc9 to your computer and use it in GitHub Desktop.
implement our own `new` keyword
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 myNew = (constructor, ...args) => { | |
// 1. create an object based on constructor.prototype | |
const obj = Object.create(constructor.prototype) | |
// 2. run constructor with this set to the above object | |
const result = constructor.call(obj, ...args) | |
// 3. if return value is object, user that. if not use the newly created one | |
if (result instanceof Object) { | |
return result | |
} | |
return obj | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment