Created
December 11, 2013 23:32
-
-
Save rauschma/7920504 to your computer and use it in GitHub Desktop.
This is roughly how one would implement 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
function newOperator(Constr, args) { | |
var inst = Object.create(Constr.prototype); | |
var result = Constr.apply(inst, args); | |
if (typeof result === 'object' && result !== null) { | |
return result; | |
} | |
return inst; | |
} |
Make that if (typeof result === 'function' || (typeof result === 'object' && result !== null)) {
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi axel, I'm not very experienced and I'd like to ask you a question, why is this way of creating objects better than calling directly to the constructor?
And the other one, is, the following piece of code makes any sense or has no advantage?
Thank you
Call it with