Calling function within another

Asked

Viewed 1,242 times

1

I have the following code

 function nomes() {

     function funcao() {
         alert("teste");


     }

       function funcao2() {
         alert("teste2");
     }

 }   


 
<input class="todas" id="checkall" type="checkbox" onclick="funcao2();">

When trying to execute function 2 through checkbox the following error occurs: funcao2 is not defined

What is the correct way to call this function ?

  • 2

    I removed my answer because it only worked if I declared the functions differently and not the way your code is (that’s why it worked in my tests). Before I put another answer, I wanted to know what is your intention by placing one function within the other. The way it is there, these internal functions are only accessible within the object nomes(), even if you did nomes.funcao2.

  • Why not put all functions separately instead of within the function nomes() ? What exactly are you trying to do?

  • I thought I’d better do it myself.

1 answer

3


The problem you encountered is due to the scope of the function. You will only be able to access the function2 after accessing the name, because the first one is nested in the second one. For this it needs to be linked to an object outside the function.

<html>
<head>
<script language="javascript">
function nomes() {

     this.chamada1 = function funcao() {
         alert("teste");
     }

     this.chamada2 = function funcao2() {
         alert("teste2");
     }
 }  

 var fChamada = new nomes();
</script>
</head>
<body>
<input class="todas" id="checkall" type="checkbox" onclick="fChamada.chamada2();">
</body>
</html>

The above solution works, however, there are several different ways to do it depending on the goal you intend to achieve.

:)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.