Skip to content

Instantly share code, notes, and snippets.

@davepacheco
Last active February 19, 2016 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davepacheco/d19fc0580d3ab49c3ff0 to your computer and use it in GitHub Desktop.
Save davepacheco/d19fc0580d3ab49c3ff0 to your computer and use it in GitHub Desktop.
JavaScript constructors (even when invoked with "new") can return values of unrelated classes.
/*
* Demo: a JavaScript constructor function, even when invoked with "new", can
* return a completely different object, even one from a completely different
* class.
*/
var counter = 0;
var lastMyClass;
function MyClass()
{
this.myc_value = counter++;
lastMyClass = this;
console.error('constructed MyClass with value ', this.myc_value);
}
function MyOtherThing(wat)
{
if (wat) {
return (lastMyClass);
}
}
/* Construct MyClass: value = 0 */
console.error(new MyClass());
/* Construct MyClass: value = 1 */
console.error(new MyClass());
/* Construct new MyOtherThing */
console.error(new MyOtherThing(false));
/*
* Use constructor for MyOtherThing to return an instance of MyClass (!)
*/
var x = new MyOtherThing(true);
console.error('new MyOtherThing(true): properties: ', x);
console.error('new MyOtherThing(true): instanceof MyClass: ',
x instanceof MyClass);
console.error('new MyOtherThing(true): instanceof MyOtherThing: ',
x instanceof MyOtherThing);
constructed MyClass with value 0
{ myc_value: 0 }
constructed MyClass with value 1
{ myc_value: 1 }
{}
new MyOtherThing(true): properties: { myc_value: 1 }
new MyOtherThing(true): instanceof MyClass: true
new MyOtherThing(true): instanceof MyOtherThing: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment