Access variable / parameter of a function within another function

2

I have the following function:

 function criarDataset(field, constraint, sorFields)
 {
    totalTarefasAtrasadas = buscarTarefasAtrasadas();

    function buscarTarefasAtrasadas()
    {
       usuario = constraints[0].finalValue;
       return = 6;
    }
}

Can the user variable receive the value of the constraints parameter of the main function?

    
asked by anonymous 03.06.2016 / 19:34

2 answers

3

After editing the question that Bacco asked, I realized that I had misunderstood. I went in the title and did not see that one function is inside the other, even because the indentation is not without default. In this case you do not have to do anything, just access the variable, the already-questionable code would already work without any changes, you just have to test. An internal function accesses all variables from the outermost scope, so buscarTarefasAtrasadas() "sees" the buscarTarefasAtrasadas() variables.

 function criarDataset(field, constraint, sorFields) {
    totalTarefasAtrasadas = buscarTarefasAtrasadas();

    function buscarTarefasAtrasadas() {
        usuario = constraint;
        console.log(usuario);
        return 6;
    }
}

criarDataset("a", "b", "c");

Now if the problem is to have two separate functions you can also pass it as a parameter to the other function. Functions should always communicate through parameters and return.

 function criarDataset(field, constraint, sorFields) {
     totalTarefasAtrasadas = buscarTarefasAtrasadas(constraint);
}

function buscarTarefasAtrasadas(constraint) {
    usuario = constraint;
    console.log(usuario);
    return 6;
}

criarDataset("a", "b", "c");

There are other ways of solving this case, but it is gambiarra and I will not go through.

    
03.06.2016 / 19:39
2

There are cases where you need to access the scope of built-in functions within Closure . And this is a possibility that javascript allows, because it does not have a closed scope. But it is good to be careful because the variable is used as reference and not value. Therefore, any changes after your call can affect the result of your function.

If you want / need, a possible solution would be:

function criarDataset(field, constraint, sorFields) {
  var totalTarefasAtrasadas = buscarTarefasAtrasadas();
  function buscarTarefasAtrasadas()
  {
    var usuario = constraint[0].finalValue;
    return 6;
  }
}

What in some cases may not be a gambiarra.   If you have any questions you can look for more about: Hoisting, Closure in javascript.

    
03.06.2016 / 20:10