0

Consider the code:

function foo()
{
    console.log('foo');
}

function bar()
{
    var foo = 5;
    foo(); // (*)
}

How to make (*) refer to outer function instead of local variable?

3
  • In the ideal situation, you would put each of these into a module, and require the modules as necessary to avoid all scoping ambiguity. Commented Nov 13, 2014 at 18:00
  • @ssube, not in my case, it is little code, but name is good (explanatory), that is why I have used it twice. Sure, I could go with underscore, but it is ugly for me since the scopes are different. Commented Nov 13, 2014 at 18:03
  • Not sure where underscore gets involved; I meant that if you have two different objects (or types, or what have you) with the same name, it may be an indication that you should split your code into modules (or namespaces). Wrapping function foo() in var otherFoo = {foo: function... resolves your issue, which is what modules do. Commented Nov 13, 2014 at 18:09

2 Answers 2

1

If the outer scope is the global scope, you can do

window.foo(); // assuming you're in a browser

If not, then you're out of luck. Give the local variable another name.

An example of when you're out of luck:

window.onload = function() {
    function foo()
    {
        console.log('foo');
    }

    function bar()
    {
        var foo = 5;
        foo(); // (*)
    }
}

The scope of the anonymous "load" handler function has no name, or any other handle by which the code in function "bar" could indicate that it wanted a reference to that "foo" instead of the local one.

Note that Coffeescript explicitly disallows this; it won't allow a local symbol to hide a more global one. (That's a controversial feature of the language, before you jump on the Coffeescript train.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for educational answer!
1

If your function is global you can use:

window.foo()

More info: http://www.w3schools.com/js/js_function_invocation.asp

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.