0

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.

1

2 Answers 2

1

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

Comments

0

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();

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.