user3633595
user3633595

Reputation: 107

Is it possible to use inner functions in JavaScript?

How can I get access to my y() function?

function x() {
    function y() {
        return 1;
    }
}

Is it possible at all?

Upvotes: 0

Views: 48

Answers (4)

Ben Bartle
Ben Bartle

Reputation: 1080

One way is to return it out of the scope

function x() {
    function y() {
        return 1;
    }
    return { 
        y:y         
    };
}

Whenever you call x(), it returns an object with the function y as a member

var a = x();
a.y();  //this returns 1

This is similar to the revealing module pattern described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FClosures

Also good to read up on closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FClosures

Upvotes: 0

milagvoniduak
milagvoniduak

Reputation: 3254

You can get access to your y function inside of the scope of the x function Only. But you can get access to the y function if you return it from your x function or assign it to a global variable or to the variable that is in scope outside of your x function. This is also know is closure, your y function will keep the reference in memory to the scope it was created in if you pass it around.

function x() {
    var anotherNum= 2;
    function y() {
        return 1 + anotherNum;
    }

    return y;
}

Now you can get the y function along with the scope it was created in. Notice that it will use anotherNum in the computation as it was created in the x function.

var yFunc = x();
console.log(yFunc()) // will print 3

Upvotes: 0

Guffa
Guffa

Reputation: 700362

You mean access it from outside the function x?

That's not possible, the function y doesn't exist when x is not running. It's declared locally inside x so it's only accessible inside x.

To make it accessible outside x you need to expose a reference to it outside the function. If you expose a reference to it, it survives after the function ends. For example:

function x() {
  function y() {
    return 1;
  }
  return y;
}

// get the reference to y
var f = x();
// call y
f();

Upvotes: 0

Ry-
Ry-

Reputation: 224942

It is scoped to x, kind of like:

function x() {
    var y;
}

So, yes, from within x, and no otherwise.

If you wanted it to be, you could create it as a property on x:

var x = (function () {
    function x() {
        …
    }

    function y() {
        …
    }

    x.y = y;

    return x;
})();

Upvotes: 2

Related Questions