Created
January 26, 2018 18:32
-
-
Save misterussell/4166ef1d285f21f6c1ac31d82ace20bd to your computer and use it in GitHub Desktop.
Replicate the unary new operator
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
function nouveau(Constructor){ | |
let args = Array.prototype.slice.call(arguments); | |
function createNew(func){ | |
const newObj = Object.create(func.prototype); | |
return function() { | |
func.apply(newObj, arguments) | |
return newObj; | |
}; | |
}; | |
return createNew(args[0])(...args.slice(1)) | |
} | |
function Alien(name, age){ | |
this.name = name; | |
this.age = age; | |
} | |
let facehugger = nouveau(Alien, 'Jackie', 1); | |
let et = nouveau(Alien, 'E.T.', 100) | |
console.log(facehugger); | |
console.log(et); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment