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();
});
}