kwagjj
kwagjj

Reputation: 807

How to access a inner nested function from outside?

Here's a sample code of the situation that I'm stuck in:

    <script>
    var mod = (function(){
        var inn1;
        function innfunc(){

        }
    }()); //mod is self expression function
    </script>

Suppose that HTML includes this javascript code and I would like to open my Java console and call the innfunc() or the variable inn1, then what can I write?

perhaps something like: mod.innfunc()?

Upvotes: 2

Views: 90

Answers (4)

ItsJonQ
ItsJonQ

Reputation: 202

+1 to what the others have said. I guess they beat me to it, haha.

I've added an example of stuff you can keep private within the function as well:

var mod = (function() {

    var publicText = 'Public!';
    var privateText = 'Private';

    var func1 = function() {
        console.log('hi');
    };

    var func2 = function() {
        console.log('there');
    };

    return {
        hi: func1,
        there: func2,
        publicText: publicText
    };
})();

mod.hi();
mod.there();

console.log(mod.publicText);

// This will fail, since the object.key privateText was never defined
console.log(mod.privateText);

Hope this helps!

Upvotes: 0

Sachin Jain
Sachin Jain

Reputation: 21842

You have executed an anonymous function and assigned the result of that function to mod. You no longer have access to that anonymous function or any of its properties.

If you want to access any of its properties later, there are multiple ways to do this. One of them is:

Return an object having properties which you need outside of this function

var mod = (function() {
  var inn1 = 'somevalue';

  var innfunc = function() {
  };

  return {
    inn1: inn1,
    innfunc: innfunc
  };
}()); //mod is self expression function

Now, you can access it as mod.innfunc()

Upvotes: 0

Jyoti Prakash
Jyoti Prakash

Reputation: 1260

try this:

 var mod = function(){

    this.inn1 = "Hello";

    this.innfunc = function(){
      console.log('Here');
    }

  }; 
  var x = new mod();
  console.log(x.inn1);
  x.innfunc();

you can use this to make variables and methods public

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173562

You have to expose a "public interface" by returning it from inside the function:

return {
    inn: inn1,
    innfunc: innfunc
}

Then you can access them using mod.inn and mod.innfunc.

Upvotes: 1

Related Questions