Reputation: 277
I wrote a program like this:
function a(x,y,z) {
function b(foo,bar) {};
function c(foo,bar) {};
function d(foo,bar) {};
function e(foo,bar) {};
function f(foo,bar) {};
}
I call the function this way:
for(var i=0; i<5; i++) { charts[i] = a(x[i],y[i],z[i])}
x,y and z are global arrays of length 5 and some properties.
Now, the loop gets executed before page load and all the functions for each of the array is also executed as expected (There are event listeners bound to elements in these functions)
Let's say I want to access some local variables from b,c,d,e or f "after" page load, when an event is invoked, how do i do it? I'm talking about "scope" here I think.
Do I have to make the whole thing an object?
Also, there are local variables inside b,c,e and f (locally declared and not using "this"). There are also variables inside of a which is accessed by b,c,d,e and f (Again, locally declared, not using "this")
Thanks!
Upvotes: 1
Views: 211
Reputation: 793
You can simple create a new object inside a and return that object.
var a = function (x, y, z) {
var result = {};
var outerVal = x;
result.b = function (foo, bar) { return foo + bar; };
result.c = function (foo, bar) { return outerVal + result.g + z}; //closure
result.d = function (foo, bar) { };
result.e = function (foo, bar) { };
result.f = function (foo, bar) { };
result.g = y;
//If you want to execute the functions you can do so
result.bValue = result.b(x, y);
result.c(y, z);
return result;
};
var anA = a(1, 2, 3);
console.log(anA.bValue); //3
console.log(anA.b(2, 5)); //7
console.log(anA.c()); //6
Upvotes: 2
Reputation: 1234
What Amberlamps said, you cannot access local variables from outside of the scope they are created, meaning your function a cannot "see" any variables created in b, c, d, e, f. You could either create some global variables (global to b, c, d, e and f) or you could consider writing a closure:
var something = (function () {
var globalOne = null,
globalTwo = null;
//...
return {
a: function (x, y, z) {
something.b(foo, bar);
something.c(foo, bar);
},
b: function (foo, bar) {
},
c: function (foo, bar) {
}
// etc.
};
}());
This could be a little overkill for what you're trying to do, but what's nice with the closure is that your globals globalOne and globalTwo cannot be modified by the client.
Upvotes: 0