Last active
February 19, 2016 17:56
-
-
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.
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
/* | |
* 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); |
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
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