首页 > 解决方案 > 如果对象实例不存在,如何禁用方法调用(javascript)

问题描述

如果该实例不存在,有没有办法不从函数对象(它的实例)调用方法?

这是我的粘性侧边栏功能,它有两种方法;init() 和 updateSticky();

function stickySideBar(element, options = {}) {
    var _this = this;

   _this.init = function () {}

   _this.updateSticky = function (timeout) {
     //this is actually just a debouncer that calls init method
    }
}

我想在窗口调整大小时使用这个 updateSticky

$(window).on("resize", function () {
    newsletterBlog.updateSticky();
    sideBarBlog.updateSticky();
    if ($(productsSticky.element).length > 0) {
        productsSticky.updateSticky();
    }
});

现在我使用 if 循环来检查元素是否存在,但我想在该函数的实例中执行此操作

如果我没有 if 循环,我会得到“未捕获的 TypeError:e.updateSticky 不是函数”。

干杯

编辑

这是功能

function stickySideBar(element, options = {}) {
    var _this = this;

    console.log("_this :>> ", _this);

    //declared element
    _this.debouncer;
    _this.element = element;

    if ($(_this.element).length === 0) {
        return;
    }

    // declared options
    _this.parentElementClass = options.parentElementClass;
    _this.wrapClass = options.wrapClass;
    _this.activeStickyClass = options.activeStickyClass;
    _this.top = options.top;
    _this.width = options.width;
    _this.activeBottomClass = options.activeBottomClass;
    _this.disableOnMobile = options.disableOnMobile ? options.disableOnMobile : true;

    _this.breakpoint = 992;

    _this.init = function () {

    };

    _this.updateSticky = function (timeout) {
        if ($(_this.element).length === 0) return;
        var timeoutVal = timeout ? timeout : 100;

        clearTimeout(_this.debouncer);
        _this.debouncer = setTimeout(function () {
            _this.init();
        }, timeoutVal);
    };

    return _this.init();
}

标签: javascriptjquerymethodsdebounce

解决方案


推荐阅读