循环遍历JS OOP中的对象数组和运行方法

时间:2018-06-02 21:47:05

标签: loops oop methods

我在这里学习Javascript OOP(不是ES6),我对这个伟大的社区有疑问:

在此代码的末尾,您有一个for循环生成一些点击侦听器,我发现自己丢失了,因为allCars[i]没有工作Uncaught TypeError: Cannot read property 'start' of undefined,如果我替换了i一个像0这样的编码索引的变量是有效的,我不明白为什么 Codepen:https://codepen.io/marcosdipaolo/pen/oyjQBN

非常感谢。

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

0 个答案:

没有答案