How to access a function inside a function?

Today, my question asks how do I access a function inside a function. So, for example, I have a button, and if I click on it, it will warn. The fact is that if you have a function surrounding the function, the internal function with a warning will not warn.

Here is an example:

HTML:

<button onclick="doStuff()">Alert</button> 

JS:

 function nothing() { var doStuff = function() { alert("This worked!") } } 

therefore, the doStuff() function will not work. Can someone help me find a way to access it?

+5
source share
3 answers

@Joseph the Dreamer is ultimately correct, but if you were dead when you called a function nested in another function, you could use the OOP approach.

Create an object of class "javascript" and point your function to "this":

 function Nothing() { this.doStuff = function() { alert("works"); } } 
  • Then you add the id to your button,
  • along with a click event listener

Then, inside the click event, you can call doStuff in the Nothing "Class" function as follows:

 var object = new Nothing(); object.doStuff(); 

https://jsfiddle.net/me7fek5f/

+1
source

You can not. This is because it is enclosed in an area that you cannot get globally. The only way to access it is to expose it somewhere outside of nothing .

+1
source

Is this a home issue?

You will probably be asked to do something like this:

 function nothing() { var doStuff = function() { alert("This worked!") } var yourButton = getYourButton(); attachClickListener(yourButton, doStuff); 

The getYourButton and attachClickListener implementations are left to the reader.

0
source

Source: https://habr.com/ru/post/1235838/


All Articles