Access a function’s variable/parameter within another function

Asked

Viewed 2,126 times

2

I have the following function:

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

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

The user variable can receive the value of the parameter constraints of the main function?

2 answers

3


After the issue of the question that Bacco asked was that I realized that I had misunderstood. I went to the title and did not see that one function is inside the other, because the indentation is not without pattern. In this case you do not need to do anything, just access the variable, the code already asked would already work without changes, just test. An internal function accesses all variables of the outermost scope, so buscarTarefasAtrasadas() "sees" the variables of buscarTarefasAtrasadas().

 function criarDataset(field, constraint, sorFields) {
    totalTarefasAtrasadas = buscarTarefasAtrasadas();
    function buscarTarefasAtrasadas() {
        usuario = constraint;
        console.log(usuario);
        return 6;
    }
}

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

I put in the Github for future reference.

Now, if the problem is having 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 to solve this case, but it’s a scam and I won’t pass.

2

There are cases where it is necessary to access the scope of internal functions within Closure. And this is a possibility that javascript allows, because it has no closed scope. But it is good to be careful because the variable is used as reference and not by value. Therefore, any subsequent changes to your call may affect the outcome 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;
  }
}

Which in some cases might not be a scam. If you have any questions you can search more about : Hoisting, Closure javascript.

Browser other questions tagged

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