Dharmesh
Dharmesh

Reputation: 570

javascript prototype variable creates reference

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.

Upvotes: 1

Views: 115

Answers (2)

Dancrumb
Dancrumb

Reputation: 27539

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.

Upvotes: 3

Misters
Misters

Reputation: 1347

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

Upvotes: -1

Related Questions