Почему в функции свойство undefined, а в консоли выводится верно?

Есть функция:

...
  this.works = {
    /**
     * Methods for working with the work page.
     *
     */
    containers: {
      h1: $('.page-work__article h1'),
      p: $('.page-work__article p'),
      counters: $('.info__counters')
    },
    show: function(background){


    },
    hide: function(background){
      console.log(this.containers);
      $('.page-work__content__controls,.page-work__sliderwrap').slideUp();
      this.containers.h1.animateCss('fadeOutDown faster2x',function(){
        this.containers.h1.removeClass('animationEnd');
        this.containers.p.animateCss('fadeOutDown faster2x',function(){
          this.containers.p.removeClass('animationEnd');
          this.containers.counters.animateCss('fadeOutDown faster2x',function(){
            this.containers.counters.removeClass('animationEnd');
            $('.page-work__bgoverlay').css({'background-image':'url(' + background + ')'}).addClass('page-work__bgoverlay--visible');
          });
        });
      });

    }

  }
...


При срабатывании выводится ошибка:
Uncaught TypeError: Cannot read property 'h1' of undefined
в этой строке this.containers.h1.animateCss. Вывожу в консоли: console.log(this.containers);, выводится объект. все нормально, но почему тогда выводится ошибка?
  • Вопрос задан
  • 100 просмотров
Решения вопроса 1
Vlad_IT
@Vlad_IT Куратор тега JavaScript
Front-end разработчик
Потому, что
this.containers.h1.animateCss('fadeOutDown faster2x',function(){ 
// тут теряется контекст this
        this.containers.h1.removeClass('animationEnd');
        this.containers.p.animateCss('fadeOutDown faster2x',function(){
          this.containers.p.removeClass('animationEnd');
          this.containers.counters.animateCss('fadeOutDown faster2x',function(){
            this.containers.counters.removeClass('animationEnd');
            $('.page-work__bgoverlay').css({'background-image':'url(' + background + ')'}).addClass('page-work__bgoverlay--visible');
          });
        });
      });

Чтобы исправить, используйте стрелочные функции, или там где у вас console.log напишите
var self = this;
и используйте self вместо this
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 11:14
65000 руб./за проект
19 апр. 2024, в 11:08
5000 руб./за проект
19 апр. 2024, в 10:59
150000 руб./за проект