javascript严格模式下的全局变量

时间:2018-10-08 14:16:04

标签: javascript this global

我不断收到错误消息:

“未捕获的TypeError:无法读取未定义的属性'hasClass'”

我知道它与全局变量和范围有关,但我不知道。任何帮助将不胜感激。

jQuery(function($) {
"use strict";

var global = this;
var carousel = null;

function mobileOnlySlider(carousel) {

    carousel = $('.woocommerce-product-gallery__wrapper').slick({

        // normal options...
        infinite: false,
        adaptiveHeight: true,
        dots: true,

    });//slick slider init
}//mobileOnlySlider function


mobileOnlySlider(global.carousel);

    function resetSlick(carousel) {
        $(window).on('resize', function() {
            if ($(window).width() > 768 ) {
                if (carousel.hasClass('slick-initialized')) {
                    carousel.slick('unslick');
                }
                else{
                    console.log("returned nothing.");
                    return;
                }
            }
            else {  
                if (carousel.hasClass('slick-initialized')) {
                    //do nothing
                    return;
                }
                else{
                    mobileOnlySlider(global.carousel);
                }
            }
        });//window resize
    }//function resetclick

resetSlick(global.carousel);


})();//plain js version of $window ready

1 个答案:

答案 0 :(得分:0)

您要在局部范围内重新定义全局变量

var carousel = null;

function mobileOnlySlider(carousel) {

    carousel = $('.woocommerce-product-gallery__wrapper').slick({

        // normal options...
        infinite: false,
        adaptiveHeight: true,
        dots: true,

    });//slick slider init
}//mobileOnlySlider function

在此方法中,carousel是一个局部变量,而不是您期望的全局变量-并且在您这样调用时:

mobileOnlySlider(global.carousel);

全局变量未更新


一种选择是从该方法返回值,并相应地更新变量

var carousel = null;

function mobileOnlySlider() {

    return $('.woocommerce-product-gallery__wrapper').slick({

        // normal options...
        infinite: false,
        adaptiveHeight: true,
        dots: true,

    });//slick slider init
}//mobileOnlySlider function

// elsewhere
carousel = mobileOnlySlider();