Javascript-форум (https://javascript.ru/forum/)
-   Javascript под браузер (https://javascript.ru/forum/css-html/)
-   -   Область видимости this в методе push (https://javascript.ru/forum/css-html/54555-oblast-vidimosti-v-metode-push.html)

Jekel 22.03.2015 17:39

Область видимости this в методе push
 
Здраствуйте, как дать доступ к this анонимной функции внутри метода push?
Пример:
g.module({
    create: function(){
        this.beep = g.sounds["beep"];
        this.vacuum = g.sounds["vacuum"];
        this.vacuum.endArr.push(function() {
            // другие операции
            this.beep.play(); // TypeError: this.beep is undefined
        });
    }
});

nerv_ 22.03.2015 18:14

function() {
    // your code here
}.bind(this);

Safort 22.03.2015 18:16

Создать переменную, ссылающуюся на this?

g.module({
    create: function(){
        this.beep = g.sounds["beep"];
        this.vacuum = g.sounds["vacuum"];
        var _this = this;
        this.vacuum.endArr.push(function() {
            // другие операции
            _this.beep.play(); // TypeError: this.beep is undefined
        });
    }
});

nerv_ 22.03.2015 18:31

верное решение - es6 arrow function :)

Jekel 22.03.2015 18:49

Спасибо большое за ответы, все работает хорошо. Я пробовал с bind'ом ранее, но не работало, а теперь все ок)


Часовой пояс GMT +3, время: 08:14.