Atario
Atario

Reputation: 1390

In Javascript, how can I reference a function-scoped variable from a function called within that function but defined elsewhere?

I have a Javascript function something like this, defined in a place I can't change it:

foo.customSave = [];

foo.save = function() {
    var saveString = 'initial value';
    // stuff about saveString here
    for (i in foo.customSave) { foo.customSave[i](); }
    // more stuff about saveString here, including actually saving it
};

Then I have my own code like this:

bar.init = function() {
    // other init stuff here
    foo.customSave.push(function() {
        saveString += 'something meaningful here';
    });
    // more other init stuff here
};

bar.init() is called at an appropriate time (which is to say, before foo.save() is called). The problem seems to be that saveString is not defined when I try to add 'something meaningful here' to it (putting a console.log call there confirms this).

Is there any way my customSave function can access that string, or am I stuck?

Upvotes: 0

Views: 70

Answers (2)

wmock
wmock

Reputation: 5492

Given that you can't modify the function associated with foo.save, there is no way you can modify the saveString variable. The reason for this is because saveString is a local variable that is scoped to function associated with foo.save. As a result, you can call the function, but it basically acts as a black box where you can't access the variables defined it in (in fact, without looking at the source code, you wouldn't even know that the saveString variable existed).

Within the function associated with bar.init, you're creating a new function object each time bar.init is called and pushing it to an array. And because you haven't used var to declare the saveString variable, JavaScript will try to find the saveString variable within the function being pushed to an array. Since it can't find the declaration there, JavaScript will continue looking up the variable in the next outer scope which the the function associated with bar.init. Since it can't find it there either, JavaScript will lastly try to find it in the global scope (and won't have success there either).

Hope that helps, but long story short, without being able to modify foo.save, you're stuck.

Upvotes: 1

Sorin C
Sorin C

Reputation: 994

How about adding saveString as a property of foo?

Like so:

foo.customSave = [];

foo.saveString = '';

foo.save = function() {
    foo.saveString = 'initial value';
    // stuff about saveString here
    for (i in foo.customSave) { foo.customSave[i](); }
    // more stuff about saveString here, including actually saving it
};

Then:

bar.init = function() {
    // other init stuff here
    foo.customSave.push(function() {
        foo.saveString += 'something meaningful here';
    });
    // more other init stuff here
};

Upvotes: 0

Related Questions