Reputation:
I have a function something like this:
var func1 = function () {
var apple;
//Some other code
};
and I have passed the function as a parameter for some other function
control(func);
Now, I want to access the variable apple in the control function. func1.apple
doesn't work. Does anyone have an idea how this is do-able?
Upvotes: 1
Views: 66
Reputation: 1790
I think what you may be looking for is the constructor pattern
var func1 = function () {
this.apple = "My Apple";
};
var myFuncInstance = new func1();
myFuncInstance.apple; // "My Apple"
Upvotes: 0
Reputation: 224859
It’s not really possible using that sort of syntax without changing the function. func1.apple
doesn’t run apple
, and something like func1().apple
would have already run apple
. If you just want to return something, then do so using return
:
var func1 = function() {
var apple;
…
return apple;
};
var apple = func1();
Or return an object if you have several values to return:
var func1 = function() {
var apple;
…
return {apple: apple};
};
var apple = func1().apple;
If you need the value during the function’s run, the only* way to accomplish this is to use another callback within your callback:
var func1 = function(useApple) {
var apple;
…
useApple(apple);
…
};
func1(function(apple) {
// Do something with apple
});
* Properties are another way, but they count as callbacks and are evil :)
Upvotes: 2