var func = function(){
this.innerVar = 'hello';
}
console.log(func.innerVar); // it prints undefined
can I access the variable innerVar from outside?
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);
var obj = new func();,.apply(obj); :D
newkeyword, 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.this, which can be different in each call. If you want to associate some data to the function itself, you should usevar func = function(){}; func.innerVar = 'hello';