Last active
November 30, 2015 00:13
-
-
Save sylvainpolletvillard/fcdd71c6af9dd151a3d4 to your computer and use it in GitHub Desktop.
Problems with constructors in JS
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
// 1) it is dangerous to have a `constructor` property, but not forbidden | |
function Car(model){ | |
this.model = model; | |
this.speed = 0; | |
} | |
function Car2(model, constructor){ | |
this.model = model; | |
this.constructor = constructor; | |
this.speed = 0; | |
} | |
var golf = new Car("Golf"); | |
golf.constructor === Car; // true | |
var golf2 = new Car2("Golf", "Volkswagen"); | |
golf2.constructor === Car2; // false ! | |
// 2) forgetting the new operator does not throw error, but can cause huge collateral damage | |
var toyota = Car("Toyota","Yaris"); // oops, forgetted new | |
console.log(window.model); // Yaris ; now we have a global leak | |
console.log(window.constructor); // Toyota ; oh shit, we also overridden Window. Greeeat | |
// 3) instanceof can be fooled in multi DOM environments: http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ | |
// 4) instance can be fooled by reference to another prototype | |
function foo() {} | |
var bar = { a: ‘a’}; | |
foo.prototype = bar; // Object {a: “a”} | |
baz = Object.create(bar); // Object {a: “a”} | |
baz instanceof foo // true. oops. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment