views:

21

answers:

1

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
+1  A: 

You don't assign a new this.data= {} in the ExtendedClass constructor. So each ExtendedClass instance inherits the data object from its prototype BaseClass instance. This is a single Object! Write lname to it from one instance and all the instances will see the change.

JavaScript's constructors and prototypes are a confusing mess. You don't usually want to be using an instance (constructed with missing arguments) as the basis for a class. This is only one of the many errors that will result.

Also, in the ExtendedClass constructor writes a new, separate hello method to every instance, instead of sharing the same function between instances as you'd normally do with a prototype.

You've probably got confused by some poorly-written JS OOP tutorial code, which is not surprising since most examples out there are pretty terrible. See this question for a (long!) discussion of the various more-consistent approaches to OO in JS.

bobince