1

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
1

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.