1

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

Deadpool
  • 7,811
  • 9
  • 44
  • 88

4 Answers4

3

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();
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
2

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();
Zenoo
  • 12,670
  • 4
  • 45
  • 69
2

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

Jeson Dias
  • 883
  • 2
  • 11
  • 26
1

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.

31piy
  • 23,323
  • 6
  • 47
  • 67