0

How do I access a variable that is defined within a function like this:

var functionVar = function(){
  this.var = 1;
}

console.log(functionVar().var); //MH - obviously this doesn't work, but I'm looking for the command that will log that variable
4
  • "functionVar.var" doesn't work ? Why adding parenthesis to a variable ? Commented Aug 9, 2012 at 14:42
  • 4
    That's not a "variable" - it's an object property. Commented Aug 9, 2012 at 14:43
  • Ah true, it's not a instance. Commented Aug 9, 2012 at 14:45
  • That's a wrong example, but if you are looking for a way to access variables defined in a function (local variables) then the answer is "you can't". Commented Aug 9, 2012 at 15:04

2 Answers 2

4

You can access like this,

var functionVar = function(){
  this.var = 1;
}

 var o = new functionVar();
 alert(o.var)​
Sign up to request clarification or add additional context in comments.

2 Comments

That's a property on the constructed object. Not a variable. Are we certain this function was meant to be used as a constructor?
Yes, it's not a variable. My bad english.
0

a new will do the trick.

var functionVar = function(){
  this.var = 1;
}

console.log(new functionVar().var);

Though not sure what you are trying to achieve by using this code.

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.