Last active
August 29, 2015 14:04
-
-
Save svanellewee/d47156b0d2d024e64af2 to your computer and use it in GitHub Desktop.
Never declare variables on prototypes!
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
var Foo = function (name) { this.name = name; }; | |
Foo.prototype.data = [1, 2, 3]; // setting a non-primitive property | |
Foo.prototype.showData = function () { console.log(this.name, this.data); }; | |
var foo1 = new Foo("foo1"); | |
var foo2 = new Foo("foo2"); | |
// both instances use the same default value of data | |
foo1.showData(); // "foo1", [1, 2, 3] | |
foo2.showData(); // "foo2", [1, 2, 3] | |
// however, if we change the data from one instance | |
foo1.data.push(4); | |
// it mirrors on the second instance | |
foo1.showData(); // "foo1", [1, 2, 3, 4] | |
foo2.showData(); // "foo2", [1, 2, 3, 4] |
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
function Foo(name) { | |
this.name = name; | |
this.data = [1, 2, 3]; // setting a non-primitive property | |
}; | |
Foo.prototype.showData = function () { console.log(this.name, this.data); }; | |
var foo1 = new Foo("foo1"); | |
var foo2 = new Foo("foo2"); | |
foo1.data.push(4); | |
foo1.showData(); // "foo1", [1, 2, 3, 4] | |
foo2.showData(); // "foo2", [1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment