Skip to content

Instantly share code, notes, and snippets.

@sym3tri
Created February 12, 2011 04:35
Show Gist options
  • Save sym3tri/823518 to your computer and use it in GitHub Desktop.
Save sym3tri/823518 to your computer and use it in GitHub Desktop.
How JavaScript new operator works
// constructor definition
var Foo = function() {
// when invoked with new it's as if the following implicitly happens
// Foo.prototype = {};
// this = {};
// return this;
};
// create new instance with 'new'
var x = new Foo();
// create new instance without 'new'
// Above is almost equivalent to
var y = {};
// illustration purposes only. __proto__ should not be accessed directly
y.__proto__ = Foo.prototype;
y.constructor = Foo;
y.constructor();
x.constructor === y.constructor // true
x instanceof Foo // true
y instanceof Foo // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment