Setting an instanced class property overwrites the property in all instances.
Posted
by Peter Moore
on Stack Overflow
See other posts from Stack Overflow
or by Peter Moore
Published on 2010-05-30T01:27:34Z
Indexed on
2010/05/30
1:32 UTC
Read the original article
Hit count: 628
JavaScript
|class
I have two instances of a class. Setting a property in the first instance will set it for the second instance too. Why? It shouldn't. The property is not a "prototype property".
Check the code below, what happens to Peter Griffin? Two objects are created and given the name "Peter Griffin" and "Roger Moore" but the alert boxes will say "Peter Moore" and "Roger Moore". What happened to Peter Griffin?
var BaseClass = function(){
this.name = "";
this.data = {};
this.data.lastname = "";
}
var ExtendedClass = function(){
this.setName = function(fname, lname){
this.name = fname;
this.data.lastname = lname;
}
this.hello = function(){
alert("Full name: " + this.name + " " + this.data.lastname);
}
}
ExtendedClass.prototype = new BaseClass();
pilot = new ExtendedClass();
driver = new ExtendedClass();
pilot.setName("Peter", "Griffin");
driver.setName("Roger", "Moore");
pilot.hello(); // Full name: Peter Moore
driver.hello(); // Full name: Roger Moore
© Stack Overflow or respective owner