O
O
Oleg2015-10-02 00:39:04
JavaScript
Oleg, 2015-10-02 00:39:04

How to use the thisArg argument in the ForEach method?

Here is a piece of code that works as expected (fills selected table cells with color):

function renderTour(league, $table, round) {
    var schedule = /*массив*/,
        home,
        away,
        $currentCell;
    schedule.forEach(function (match) {
        home = match[0] + 1;
        away = match[1] + 1;
        $currentCell = $table.find('tr:eq(' + home + ')>td:eq(' + away + ')');
        $currentCell.css('background-color',  'rgba(200, 100, 0, 0.2)');
    });
}

When I try to put the code into a separate function, I get an error: "$table is not defined":
function renderTour(league, $table, round) {
    var schedule = /*массив*/,
        home,
        away,
        $currentCell;
    schedule.forEach(highlight);
}

function highlight(match) {
    home = match[0] + 1;
    away = match[1] + 1;
    $currentCell = $table.find('tr:eq(' + home + ')>td:eq(' + away + ')');
    $currentCell.css('background-color', 'rgba(200, 100, 0, 0.2)');
}

The documentation describes that you can add an object as the second argument, which the function will refer to as this. However, there is no usage example, and I'm not quite sure how to use it, or even if it's something that will help me solve the problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-10-02
@ptrvch

that you can add an object as the second argument

Find the difference
schedule.forEach(highlight, $table);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question