Jordan
Jordan

Reputation: 143

Using an array in the prototype

I'm having an issue with my OOP JavaScript. If the object has an array in it and I push things in a new instance of the object it gets saved to all instances. Does anyone know what I'm doing wrong?

function Car(){}
Car.prototype.name = "";
Car.prototype.color = [];

var suv = new Car;
suv.color.push("black"); //black

var sedan = new Car;
sedan.color.push("green"); //black, green

Upvotes: 1

Views: 56

Answers (2)

Paul
Paul

Reputation: 141829

You want each instance of car to have its own array, so you should not define it on the prototype. The prototype is where you would typically put things that are shared between all instances, like functions that all Car's have, or default values for properties that haven't been defined on every instance:

function Car(name){
    if ( typeof name === 'string' )
        this.name = name;
    this.color = [];
}
Car.prototype.name = "No name"; // Default name

var suv = new Car('SUV');
suv.color.push("black");
console.log(suv.name); // "SUV"

var sedan = new Car;
sedan.color.push("green");
console.log(sedan.name); // "No name"

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

That array is on every prototype, you want:

function Car() {
    this.color = [];
}

var suv = new Car();
suv.color.push("black"); //black

var sedan = new Car();
sedan.color.push("green"); //green

Upvotes: 3

Related Questions