Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access function inside of function?

today my question is asking how I would access a function inside a function. So, for example, I have a button, and if I click it, it would alert. The thing is, if you have a function surrounding the function, the inside function with the alert would not alert.

Here's an example:

html:

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

js:

function nothing() {

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

}

so the doStuff() function would not work. Can someone help me find a way to access it?

like image 728
Victor Wei Avatar asked Oct 31 '22 15:10

Victor Wei


2 Answers

@Joseph the Dreamer is ultimately correct, but if you were dead set on calling a function that's nested in another function you could use an OOP approach.

Create a javascript "class" object and scope your function to "this":

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

Then, inside your click event you can call doStuff within the Nothing "Class" function like this:

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

https://jsfiddle.net/me7fek5f/

like image 163
Dan Beaulieu Avatar answered Nov 12 '22 14:11

Dan Beaulieu


You can't. That's because it's enclosed in a scope that you can't really access globally. The only way you can access it is to expose it somewhere outside nothing.

like image 22
Joseph Avatar answered Nov 12 '22 13:11

Joseph