In the snippet I prepared below, I have a table with some simple data. Below the table, there are two labels that account for the total age of the data in the table. The first label is calculated using a common anonymous function, the second one is using an arrow function.
I noticed that in the arrow function, this
is Window
, not the object that called the function, as in the other case. Because of this, the sum in the label results in NaN (Not a Number)
By reading the documentation , I came up with the concept of this
lexicon, but from that point I do not understand anything else. How could I circumvent the situation so that arrow function works the way I expected it to be?
window.onload = function (){
atualizaSomaIdades();
atualizaSomaIdadesArrowFunction();
}
$('.excluir').click(function (){
$(this).parent().parent().remove();
atualizaSomaIdades();
atualizaSomaIdadesArrowFunction();
});
function atualizaSomaIdades(){
var total = 0;
var rows = $('table').find('tbody').find('tr');
rows.each(function () {
total += parseInt($(this).find('td').eq(1).text());
});
$('#idade-comum').text(total);
}
function atualizaSomaIdadesArrowFunction(){
var total = 0;
var rows = $('table').find('tbody').find('tr');
rows.each(() => {
total += parseInt($(this).find('td').eq(1).text());
});
$('#idade-arrow-function').text(total);
}
td{
border: 1px solid black;
}
.negrito{
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><thead><tr><td>Nome</td><td>Idade</td><td>Ações</td></tr></thead><tbody><tr><td>João</td><td>25</td><td><buttonclass="excluir">Remover</button>
</td>
</tr>
<tr>
<td>
Carlos
</td>
<td>
16
</td>
<td>
<button class="excluir">Remover</button>
</td>
</tr>
<tr>
<td>
Artur
</td>
<td>
21
</td>
<td>
<button class="excluir">Remover</button>
</td>
</tr>
</tbody>
</table>
<span class="negrito">Total de idade:</span>
<span id="idade-comum"></span>
<span id="idade-arrow-function"></span>