2

I have a simple function, I am trying to access the instance variable. But it's giving me some error. How can I access instance variable in Javascript ? I tried below method, but not working

function Test(){
   var a=10;
}

var test=new Test();
test.a=20;

For some reason I don't want to go with the following way:

var Test={
  a:''
}
1
  • 1
    That is a local variable, you cannot access it directly. Use this.a=10 instead Commented Feb 18, 2014 at 19:43

3 Answers 3

6

You declared a as a variable local to that function, so there is no way to access it outside (as you currently have it)
If you want a to be an instance variable attach it to the object

function Test(){
   this.a=10;
}

var test=new Test();
test.a=20;
Sign up to request clarification or add additional context in comments.

3 Comments

Interestingly enough, this fiddle, at least in Chrome v32, seems to show that using var syntax still allows one to access the variable using from outside the object using test.a. Am I missing something here?
@Divey That's because you are creating a new property, not modifying the existing variable. See jsfiddle.net/3C8BK/1
@JuanMendes Whoops! Indeed I am.
2

Change it to this :

function Test(){
    this.a=10;
}

Here a good documentation on the subject : Introduction to Object-Oriented JavaScript

Comments

0

Existing answers tell you how to do it by making a a public property. If you really need a private variable, use the following code. The main reason you would use this instead of a public property is to prevent callers from setting a to invalid values.

function Test() {
   var a = 10;
   this.setA = function(val) {
        a = val; 
   };
   this.getA = function(val) {
        return a; 
   };
}

var t = new Test();
t.setA(80);
t.getA(); // 80

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.