1

I have create object lik

e this
testObj.prototype = {
    cVar: 15,
    init: function(c){
        /*initialization code*/
        this.cVar = c;
    }
};

var a = new testObj(10);
var b = new testObj(20);

Now both object's cVar values is 20. Are they sharing the variable? How i can get seperate variable for each object?

1 Answer 1

6

Yes, they're shared. For separate properties, define them inside the constructor:

function Ctor() {
    this.notShared = 1;
};

Ctor.prototype.shared = 2;
Sign up to request clarification or add additional context in comments.

4 Comments

how to access this.notShared? inside prototype.init?
this.notShared, but you must call the constructor before calling init.
This example is slightly confusing. var o1 = new Ctor(); var o2 = new Ctor(); o1.shared += 1; console.log("o1.shared = " + o1.shared + ", o2.shared = " + o2.shared); gives o1.shared = 3, o2.shared = 2. I know this is obvious, but the shared sense of it doesn't come out through this example. It'd be better if the example demonstrated the shared state by using Ctor.prototype.shared = {}
@BharatKhatri makes a good point. If you modify the shared variable on one of the instantiated objects, then it becomes "unshared" on that object (as the variable has been re-assigned on it).

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.