Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:04
Show Gist options
  • Save svanellewee/d47156b0d2d024e64af2 to your computer and use it in GitHub Desktop.
Save svanellewee/d47156b0d2d024e64af2 to your computer and use it in GitHub Desktop.
Never declare variables on prototypes!
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]
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