Scope of variables in Javascript

Asked

Viewed 108 times

1

I’m having doubts about the scope of variables in Javascript.

I’m looking to build an object called Campeonato.
I want one of your methods to receive a text from a textArea and form a Array which is an object attribute.

But you’re making a mistake! I can’t seem to create an object Array inside the object. Perhaps scope problem.

Follows the code:

var bt_start = document.getElementById('start');
var textArea = document.getElementById('lista_times');

bt_start.onclick = function()
{
   if(textArea.value == "" ||  textArea.value == null )
   {
     alert('Preencha a textArea corretamente!')
   }
   else
  {

     var campeonato = new Campeonato();
     campeonato.getTimes(textArea.value);

     alert(campeonato.ArrTimes.length);

    function Campeonato()
    {
       this.getTimes = getTimes;
       this.arrTimes = new Array();

      function getTimes(textArea)
      {

           textArea.split("\n").forEach(linha => {
           clube = linha.split(';');

           time = clube[0];
           estado = clube[1];

           arrTimes.push(new Time(time,estado));

        })
      } 

    function Time(nome, estado)
    {
        this.nome = nome; 
        this.estado = estado;
    }
  • On which line gives the error and what is the error message? Please add this information to your question, this will make it more likely to be answered.

  • Doesn’t actually run the script

  • That variable in the Championship function called arrTimes. I cannot declare it as an array (its methods are not visible in Vscode) and I cannot form an array as object attribute.

2 answers

3


This is because arrTimes does not exist in the context of its forEach, but rather in Campeonato. To fix this, just use keyword this to refer to the scope of Campeonato.

document.getElementById("testar").onclick = function () {
  const campeonato = new Campeonato();
  const textArea = document.getElementById("teste");
  campeonato.getTimes(textArea.value);
}

function Campeonato()
{
   this.getTimes = getTimes;
   this.arrTimes = new Array();

  function getTimes(textArea)
  {

     textArea.split("\n").forEach(linha => {
       clube = linha.split(';');

       time = clube[0];
       estado = clube[1];


       this.arrTimes.push(new Time(time, estado));
      console.log(this.arrTimes);
    })
  } 
}

function Time(nome, estado)
{
    this.nome = nome; 
    this.estado = estado;
}
<textarea id="teste" rows="10" cols="50"></textarea><br>
<button id="testar">Testar!</button>

1

I believe one can be used map in that case.

let times = textArea.split("\n").map((linha) => {
           clube = linha.split(';');
           time = clube[0];
           estado = clube[1];
           return new Time(time, estado);
     });

this.arrTimes.concat(times);

Browser other questions tagged

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