Mohsin Ali
Mohsin Ali

Reputation: 3

javascript: for different objects of same class copy arrays in different variables

in following code I declare two objects of class "person". problem is that when for one of the variables ("Courses") I use push method to update its values so they are copied in proto and as a consequence both objects share same "Courses" array inside there proto. i want them to have there own unique arrays.

var person = {
    Name: "John",
    Grade: 0,
    Courses:[],
    setGrade : function(y){
        this.Grade=y;
    },
    setCourse:function(t){
        this.Courses.push(t);

    },
}

var grade9 = Object.create(person);
grade9.setCourse("eng");
grade9.setCourse("math");
grade9.setGrade(9);

var grade10 = Object.create(person);
grade10.setCourse("phy");
grade10.setCourse("chem");
grade10.setCourse("bio");
grade10.setGrade(10);

debug output

thanx.

Upvotes: 0

Views: 70

Answers (2)

Jared Smith
Jared Smith

Reputation: 21926

Object.create returns an object with the prototype property set to the passed-in object. The 'instance' objects delegate to the prototype. The same prototype. In C terms they all have pointers to the same struct (the prototype) and modifying it changes the value for all the 'instance' objects (they're only pointing to it). While that isn't totally accurate its enough so for our purposes here. If you want them to all to have independent copies you'll have to add them:

personFactory = function() {
    newPerson = Object.create(person);
    newPerson.array = [];
}

myPerson = personFactory();

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

Create a factory method, and inside overshadow the property with a specific property for the current instance:

function createNewPerson() {
    return Object.create(person, { // object.create with propertiesObject to overshadow original Courses property 
        Courses: { writable: true, configurable: true, value: [] }
    });
}

var grade9 = createNewPerson();
grade9.setCourse("eng");
grade9.setCourse("math");
grade9.setGrade(9);

var grade10 = createNewPerson();
grade10.setCourse("phy");
grade10.setCourse("chem");
grade10.setCourse("bio");
grade10.setGrade(10);

Upvotes: 1

Related Questions