Skip to content

Instantly share code, notes, and snippets.

@sunderls
Created June 1, 2020 13:19
Show Gist options
  • Save sunderls/90ee0c310530063752471c5337e77cc9 to your computer and use it in GitHub Desktop.
Save sunderls/90ee0c310530063752471c5337e77cc9 to your computer and use it in GitHub Desktop.
implement our own `new` keyword
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