Created
February 12, 2011 04:35
-
-
Save sym3tri/823518 to your computer and use it in GitHub Desktop.
How JavaScript new operator works
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
// 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