1

Создаю пользователя через конструктор User, но потом когда хочу добавить его в массив через push мне выводит Uncaught TypeError: Cannot read property 'push' of undefined

В чем ошибка?

UPD: понял, что дело в том, что отдельная функция UsersList.add как бы не видит массив this.users (или я не прав?)

Но как тогда сделать отдельную функцию, чтобы он видел этот массив?

function User(firstName, lastName, regDate) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.regDate = regDate;

}


function UserList() {
    this.users = [];
}

UserList.add = function (justUser) {
    console.log(justUser);
    this.users.push(justUser);
}

let start = function () {
    while (true) {
        let fullName = prompt('Your name and surname ?');

        if (fullName === null) break;

        let fullNameArr = fullName.split(' ');
        // console.log(fullNameArr);
        let firstName = fullNameArr[0];
        let lastName = fullNameArr[1];
        let d = new Date();
        var newUser = new User(firstName, lastName, d);
        UserList.add(newUser);


    }


}
2
  • Вы вот здесь ничего не забыли сделать? - ru.stackoverflow.com/questions/1051474/…
    – user176262
    30 апр 2020 в 20:22
  • @Igor на тот момент еще не разбирался насчет галочки) спасибо!
    – Immersion
    30 апр 2020 в 20:29

1 ответ 1

3
function UserList() {
    this.users = [];
}

UserList.prototype.add = function (justUser) {
    console.log(justUser);
    this.users.push(justUser);
}

var userList = new UserList();


    ...
    userList.add(newUser);
2
  • мне теперь пишет UserList.add is not a function
    – Immersion
    30 апр 2020 в 20:32
  • @shadow1337 Зато userList.add - is a function.
    – user176262
    30 апр 2020 в 20:33

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.