Skip to content

Instantly share code, notes, and snippets.

@visnup
Last active December 17, 2015 21:09
Show Gist options
  • Select an option

  • Save visnup/5672732 to your computer and use it in GitHub Desktop.

Select an option

Save visnup/5672732 to your computer and use it in GitHub Desktop.

Today I shall remember what new does

It does exactly this:

function New(constructor) {
  // create a new object, with it's prototype set to the constructor's `prototype`
  var obj = Object.create(constructor.prototype);
  
  // call the constructor function, with `this` set to the new object
  constructor.apply(obj, [].slice.call(arguments, 1));
  
  return obj;
}

thing = New(Thing, 1, 2);     // this is the same...
sameThing = new Thing(1, 2);  // as this

and that is all. I always had an intuitive sense of what it did, but I could never explicitly enumerate them so simply and without double-checking. Pardon the [].slice.call thing; arguments is a weirdo thing that doesn't have a slice method on itself until ECMAScript 5.

Thanks to Marcus Phillips' training talk at JSConf for finally pounding this into my head.

@vicapow
Copy link

vicapow commented May 29, 2013

except when you return an object or function in the constructor that isn't a reference to the newly created instance (which is something you should probably never do but worth being aware of.)

var Person = function(){
  // `new` ignores the result of the return statement and still returns the new instance
  return 1337; // or any other none object
}

New(Person) instanceof Person // true
new Person instanceof Person  // true

var Person = function(){
  return { foo : 'bar'}; // object (or function)
}

New(Person) instanceof Person // true
new Person instanceof Person  // false

@visnup
Copy link
Author

visnup commented May 30, 2013

True. Doesn't work for New(Array, 3) either. :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment