简体   繁体   中英

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() ?

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 .

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

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()

+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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM