Looping through an array of objects and running methods in JS OOP

I’m learning Javascript OOP here (not ES6) and i have a question to this great community:

At the end of this code you have a for loop generating some click listeners and i found myself lost, since allCars[i] doesn’t work Uncaught TypeError: Cannot read property 'start' of undefined and if I replace the i variable for a harcoded index like 0 it works, and I don’t understand why.
Codepen here: https://codepen.io/marcosdipaolo/pen/oyjQBN .

Thanks a lot.

var allCars = [];
var count = 0;

var Auto = function (brand, year) {
    this.brand = brand;
    this.year = year;
    this.divsId = this.brand + this.year + '_' + count;

    /* start method */
    this.start = function () {
        window.alert('I am a ' + this.brand + ' built in ' + this.year + ' and I am starting');

    } /* /start mehod */

    $('.container.autos')
        .append('<div class="auto" id="' +
            this.divsId + '" data-brand="' +
            this.brand + '" data-year="' +
            this.year + '"><h6>I am a ' +
            this.brand + ' built in ' +
            this.year + '</h6></div>');
    allCars.push(this);
    count++;

}
/* starter objects */
var ford84 = new Auto('ford', 1984);
var peugeot95 = new Auto('Peugeot', 1995);

/* button click event */
$('#button').on('click', function () {
    var newBrand = $('#brand').val();
    var newYear = $('#year').val();
    if (newBrand && newYear) {
        var newAuto = new Auto(newBrand, newYear);
    }
});
/* Cars click events */
var divs = $('.auto');
for (var i = 0; i < allCars.length; i++) {
    $(divs[i]).on('click', function () {
        allCars[i].start();
    });
}

If after the code has run you try allCars[i] then it won’t work, because the for loop has already advanced the i variable to a value that cannot be indexed in the array.

Mutating a global variable from within a class is not good practice. All your variables should live inside your class and the class should not know about anything other than itself and what it inherits from.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.