Skip to content

Instantly share code, notes, and snippets.

@bowsersenior
Last active December 14, 2015 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bowsersenior/5136359 to your computer and use it in GitHub Desktop.
Save bowsersenior/5136359 to your computer and use it in GitHub Desktop.
Demo of JavaScript constructor property. Illustrates that the constructor property is set automatically by JavaScript, but is overwritten when a custom prototype is assigned, necessitating the constructor to be explicitly set in the prototype. For more info, refer to http://nerdstuckathome.wordpress.com/2012/11/06/a-quick-digression-about-the-co…
function Nuttin() {};
function Sumtin() {};
Sumtin.prototype = { foo: function(){} };
function SumtinElse() {};
SumtinElse.prototype = { bar: function(){}, constructor: SumtinElse };
function AnotherSumtinElse() {};
Object.defineProperty(AnotherSumtinElse, "prototype", { value: {bar: function(){}, constructor: AnotherSumtinElse }});
Nuttin.constructor;
// function Function() { [native code] }
Sumtin.constructor;
// function Function() { [native code] }
SumtinElse.constructor;
// function Function() { [native code] }
AnotherSumtinElse.constructor
// function Function() { [native code] }
Nuttin.prototype.constructor;
// function Nuttin() {}
Sumtin.prototype.constructor;
// function Object() { [native code] }
SumtinElse.prototype.constructor;
// function SumtinElse() {}
AnotherSumtinElse.prototype.constructor
// function AnotherSumtinElse() {}
var n = new Nuttin();
n.constructor;
// function Nuttin() {}
var s = new Sumtin();
s.constructor;
// function Object() { [native code] }
var se = new SumtinElse();
se.constructor;
// function SumtinElse() {}
var ase = new AnotherSumtinElse();
ase.constructor;
// function AnotherSumtinElse() {}
// fascinating detail
// explicit setting of constructor makes the property enumerable
// from: http://nerdstuckathome.wordpress.com/2012/11/06/a-quick-digression-about-the-constructor-in-javascript/
for (key in Nuttin.prototype) { console.log(key) };
// undefined
for (key in Sumtin.prototype) { console.log(key) };
// foo
for (key in SumtinElse.prototype) { console.log(key) };
// bar
// constructor
for (key in AnotherSumtinElse.prototype) { console.log(key) };
// undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment