2

Есть такой код: При вызове функции setCenter из calcMinMax я получаю ошибку:

Uncaught TypeError: this.setCenter is not a function at PanZoom.calcMinMax

Что можете подсказать? В чем ошибка?

function PanZoom(id){
    $el = $(id);
    var minZoom;
    var maxZoom;
    var currentZoom;
    this.setCenter = function(){
        var cW = $(window).width()/2 - ($el.outerWidth(true)/2);
        var cH = $(window).height()/2 - ($el.outerWidth(true)/2);
        this.panzoom(cW, cH, this.minZoom); // это работает
    };
    this.calcMinMax = function(){
        if($(window).width() < $(window).height()){
            this.minZoom = parseFloat(($(window).width() / ($el.outerWidth(true))).toFixed(4));
        }else{
            this.minZoom = parseFloat(($(window).height() / ($el.outerHeight(true))).toFixed(4));
        }
        this.currentZoom = this.minZoom;
        this.maxZoom = parseFloat((this.minZoom + 2).toFixed(4));

        if(this.currentZoom == this.minZoom) this.setCenter(1);  // это не работает
    };

    $(window).resize( this.calcMinMax );
}
1

2 ответа 2

2

Метод this.calcMinMax в качестве обработчика события resize будет вызываться в контексте window. Чтобы обеспечить правильный контекст, нужно:

$(window).resize( this.calcMinMax.bind(this) );

или

$(window).resize(() => this.calcMinMax());

Зачем вот это?

var minZoom;
var maxZoom;
var currentZoom;

Имелось в виду вот это?

this.minZoom = 0;
this.maxZoom = 0;
this.currentZoom = 0;

Какой смысл проверки?

if(this.currentZoom == this.minZoom)

если двумя строчками выше

this.currentZoom = this.minZoom;
0

у каждой функции своя область видимости this. Сделайте так:

function PanZoom(id){
    ...
    var _this = this;
    this.setCenter = function(){
        ...
        _this.panzoom(cW, cH, this.minZoom); // это работает
    };
    this.calcMinMax = function(){
        ...    
        if(_this.currentZoom == _this.minZoom) _this.setCenter(1);
    };

    $(window).resize( this.calcMinMax );
}

заодно проверьте и другие this во вложенных функциях

1
  • это не "область видимости", a "контекст вызова"
    – user176262
    18 июл 2018 в 21:09

Ваш ответ

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

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