Call function inside another [duplicate]

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 the checkbox the following error occurs: function2 is not defined

What is the correct way to call this function?

    
asked by anonymous 14.10.2017 / 07:40

1 answer

3

The problem you encountered is due to the scope of the function. You can only access function2 after accessing the name, because the first one is nested to the second. 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 this depending on the goal you intend to achieve.

:)

    
14.10.2017 / 12:19