Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created December 11, 2013 23:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rauschma/7920504 to your computer and use it in GitHub Desktop.
Save rauschma/7920504 to your computer and use it in GitHub Desktop.
This is roughly how one would implement the `new` operator in JavaScript.
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;
}
@rafinskipg
Copy link

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

function myObjectConstructor(parameter, parameter2){
  //perform private logic

  return {
    parameter: parameter,
    parameter2: parameter2
   }
}

var myObjectInstantiator = (function (Constr) {
  return function(arguments){
    var inst = Object.create(Constr.prototype);
    var result = Constr.apply(inst, arguments);
    if (typeof result === 'object' && result !== null) {
        return result;
    }
    return inst;
}
})(myObjectConstructor);

Call it with

var objectInstance = myObjectInstantiator([6,true])

@olov
Copy link

olov commented Dec 12, 2013

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