简体   繁体   中英

How to access function inside function without outer returning inner one

I have got a function 'alpha', and there is another function 'beta' inside it. If I don't return beta in alpha, then how to access beta. Is there anyway of doing this? (Like, I can access alpha writing window.alpha(), as in global context alpha becomes a property of window object, then how to access beta as property, via window dom tree)?

 <html> <head></head> <body> <script> function alpha() { console.log("hi"); function beta() { console.log("hello"); } } alpha(); //works window.alpha(); //works beta(); //it is directly not accessible. How to access it if alpha does not return it </script> </body> </html> 

alpha() is in Window Dom but why not beta? (Even not inside alpha)

在此处输入图片说明

Normally you can not do this thing either you can prefer these option but in these you have to call alpha once in order to get beta

//first option

(function alpha() { 
  console.log("hi");
  function beta() {
    console.log("hello");
  } 
  window.beta = beta;
})() 

//second option

Use this to create beta as property in alpha

function alpha() {
  this.beta = function() {
    console.log("hello");
  }
}
let alphaObject = new alpha();
alphaObject.beta();

If you don't want to return beta , you could return this and define beta as this.beta :

To access beta() , you simply need to call alpha().beta() .

 function alpha() { console.log("hi"); this.beta = () => { console.log("hello"); } return this; } alpha().beta(); 

The beta() method is private to function alpha. The way Javascript scoping works prevents you from directly accessing the inner functions . Create it as a property of alpha by using this.beta

Declare beta as a member of alpha using this :

 function alpha() { console.log("hi"); this.beta = function() { console.log("hello"); } } let a = new alpha(); a.beta(); 

You current implementation prevents JavaScript from accessing beta from outside of alpha . Read more about private functions in JavaScript.

Using this you can actually attach such methods to the instances of the function alpha . That's what I've done in this solution.

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