paulenot
@paulenot
IT Issue

Почему не получается обратиться к this в JavaScript?

Потратил вчера пару часов на написание класса. Но работать с переменными класса у меня не получилось. Тогда я решил сделать по инструкции но это тоже не работает:
var filter = {
	field: {
		sex: null,
		player: null,
		country: null,
	},
	update: {
		sex: function(){
			this.field.sex = $('#sex').value();
		},
		player: function(){
			this.field.player = $('#player').value();
		},
		country: function(){
			this.field.country = $('#country').value();
		},
	},
};
// Пробовал функцию со скобками ()
filter.update.sex;
filter.update.player;
filter.update.country;
console.log(filter);


В итоге я получаю обьект с пустыми значениями:
field:
country: null
player: null
sex: null

По моему опыту за последние пару дней - JS просто ужасно работает с классами, либо выстраиваются они очень специфически по сравнению с другими языками.

Как мне обновить данные полей используя функции обьекта/класса?
  • Вопрос задан
  • 113 просмотров
Пригласить эксперта
Ответы на вопрос 1
@GrayHorse
Ошибка в коде в том, что при вызове filter.update.country() this является объект update, а не filter.

JS код, идентичный коду на Java:
class Filter {
    static sex = null;
    static player = null;
    static country = null;

    static updateSex() {
        Filter.sex = document.querySelector("#sex").value;
    }
    static updatePlayer() {
        Filter.player = document.querySelector("#player").value;
    }
    static updateCountry() {
        Filter.country = document.querySelector("#country").value;
    }
}

Filter.updatePlayer();
console.log(Filter.player);

или
class Filter {
    constructor() {
        this.sex = null;
        this.player = null;
        this.country = null;
    }

    updateSex() {
        this.sex = document.querySelector("#sex").value;
    }
    updatePlayer() {
        this.player = document.querySelector("#player").value;
    }
    updateCountry() {
        this.country = document.querySelector("#country").value;
    }
}

const filter = new Filter();
filter.updateCountry();
console.log(filter.country);


Ну и рабочий аналог "кода" из вопроса:
class Filter {
    fields = {
        country: null,
    }
    update = {
        caller: this,
        country() {
            this.caller.fields.country = "123";
        }
    }
}
const filter = new Filter();
filter.update.country();
console.log(filter.fields.country);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы