1

I am new to object oriented javascript, hence this question can be very naive.

I have:

RIT.test = (function() {
    test.prototype.SRT = {
        someInSRT: 5
    };
    function test() {
    }
    return test;
})();

And I am doing the following:

    var v1 = new RIT.test();
    var v2 = new RIT.test();
    v1.SRT.someInSRT = 10;
    v1.SRT.someInSRT = 5;
    console.log(v1.SRT.someInSRT);
    console.log(v2.SRT.someInSRT);

Why is the value of both v1.SRT.someInSRT and v2.SRT.someInSRT both 5? I imagined that I am creating two separate instances with 'new'.

Can someone suggest me a better approach please? FYI, SRT must be an object.

0

2 Answers 2

3

When you add SRT to the prototype, you're adding a reference to an object that you've defined as

{
    someInSRT: 5
}

All new instances of the object, based on this prototype will share that refernce. Thus, v1.SRT === v2.SRT. Thus, any changes you make to v1.SRT will be visible via v2.SRT;

What you need, in this case, is something like:

RIT.test = (function() {
    function test() {
        this.SRT = {
            someInSRT: 5
        };
    }
    return test;
})();

In this way, all objects derived from RIT.test will have their own, independent value for SRT.

Sign up to request clarification or add additional context in comments.

Comments

-1

Since you are creating 2 instance of RIT.test() class, they cannot be the same.

Consider this example:

var class1 = function(value){
this.number value;
};
class1.prototype.getNumber = function(){
return this.number;
}

var number = new class1(5);
var number2 = new class1();//not value pass to the constructor here...
console.log(number.getNumber());//print 5 because the constructor is reciving a value
console.log(number2.getNumber())//null, since you have not give any value
//since you did not pass any value to the second instance to the constructor

1 Comment

That didn't answer the question at all

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.