简体   繁体   中英

global variable in javascript strict mode

I keep getting the error:

"Uncaught TypeError: Cannot read property 'hasClass' of undefined"

I know its something to do with global variables and scope but I can't figure it out. Any help would be appreciated.

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

You're redefining a global variable in local scope

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

Within this method, carousel is a local variable, not the global one you expect - and when you call it like this:

mobileOnlySlider(global.carousel);

The global variable is not updated.


One option is to return the value from that method, and update the variable accordingly

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM