javascriptfunctionscopewindow-object

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)

enter image description here


Solution

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