0
var func = function(){
   this.innerVar = 'hello';
}

console.log(func.innerVar); // it prints undefined

can I access the variable innerVar from outside?

4
  • 1
    You can if you create a new instance with the new keyword, but then you should also have good reason for actually needing an instance, otherwise you might as well just define a regular variable in a higher scope. Commented Jan 1, 2016 at 18:14
  • 3
    That's not a variable. It's property assigned to this, which can be different in each call. If you want to associate some data to the function itself, you should use var func = function(){}; func.innerVar = 'hello'; Commented Jan 1, 2016 at 18:16
  • 4
    This is almost guaranteed an XY problem question. What are you actually trying to do that makes you ask this? Commented Jan 1, 2016 at 18:24
  • 1
    Part XY problem, part just not bothering to learn the language. Commented Jan 1, 2016 at 19:18

4 Answers 4

2
var func = function(){
   this.innerVar = 'hello';
}

Now you have these options:

1) Using func as a constructor:

console.log(new func().innerVar);

2) Using the apply method on the function:

var obj = {};
func.apply(obj);
console.log(obj.innerVar);

3) Using the call method on the function (cheers to @dev-null):

var obj = {};
func.call(obj);
console.log(obj.innerVar);

4) Using the bind method on the function:

var obj = {};
func.bind(obj)();
console.log(obj.innerVar);

5) And the crazy stuff:

console.log(func.apply(func) || func.innerVar);
Sign up to request clarification or add additional context in comments.

5 Comments

@dev-null Haha, yes even better :)
or var obj = new func();,
or .apply(obj); :D
Anyone more suggestions? :D
Thanks guys... It really helped
1

That's basic

var func = function(){
   this.innerVar = 'hello';
}

console.log((new func()).innerVar);
  1. Create a object new func().
  2. Set its property innerVar this.innerVar = 'hello';.
  3. Fetch its property (new func()).innerVar

Comments

0
var Func = function(){
   this.innerVar = 'hello';
}

var func = new Func; // Creates an instance of your Func class
console.log(func.innerVar);

Comments

0
var func = function() {
  func.innerVar = 'hello';
};

func.innerVar; // undefined
func();
func.innerVar; // ‘hello'

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.