Javascript 继承此函数以发挥作用

Javascript 继承此函数以发挥作用,javascript,jquery,this,Javascript,Jquery,This,我想通过使用在单击时运行的函数来更改它,以便更清楚地编写它。这是一个有效的代码: menuHamburger.click(function () { if($(this).hasClass("closed")){ $(this).removeClass("closed"); }; subMenu.removeClass("show"); if (mainSidebar.toggleClass('a

我想通过使用在单击时运行的函数来更改它,以便更清楚地编写它。这是一个有效的代码:

    menuHamburger.click(function () {

        if($(this).hasClass("closed")){
            $(this).removeClass("closed");
        };
        subMenu.removeClass("show");

        if (mainSidebar.toggleClass('active')) {
            return true;
        }
    });
我想这样写:

    menuHamburger.click(function () {

        closedHamburderOnClick();

        if($(this).hasClass("closed")){
            $(this).removeClass("closed");
        };
        subMenu.removeClass("show");

        if (mainSidebar.toggleClass('active')) {
            return true;
        }
    });


    function closedHamburderOnClick(){
        if($(this).hasClass("closed")){
            $(this).removeClass("closed");
        };
    }

但它不起作用。如何修复它?

在这种特殊情况下,只需将
$(this)
传递到函数中,并声明要使用的参数:

menuHamburger.click(function () {

    closedHamburderOnClick($(this));

    // (removed lines here I'm fairly sure you meant to remove in the question)

    subMenu.removeClass("show");

    if (mainSidebar.toggleClass('active')) {
        return true;
    }
});


function closedHamburderOnClick(elements){
    if(elements.hasClass("closed")){         // You can get rid of this entirely
        elements.removeClass("closed");
    } // No ; after the block attached to control flow statements
}
如果您出于某种原因需要呼叫
ClosedHamburderOn单击
,以便
中的内容与您呼叫时的内容相同,您可以使用:

然后在其中使用

function closedHamburderOnClick(){
    if($(this).hasClass("closed")){         // You can get rid of this entirely
        $(this).removeClass("closed");
    } // No ; after the block attached to control flow statements
}
还有一个函数也以相同的方式处理
this
,但是
call
apply
处理参数的方式不同


但是在这种情况下,不需要调用
应用

您可以像其他任何函数一样将
$(this)
作为函数参数传递。您不必测试元素是否有类来移除它。只需执行
$(this.removeClass(“closedshow”)告诉我在你的第二个代码块中有几行你想删除。@DenysSéguret,我不认为OP的重点是
hasClass
Hamburder…嗯。我现在饿极了!
function closedHamburderOnClick(){
    if($(this).hasClass("closed")){         // You can get rid of this entirely
        $(this).removeClass("closed");
    } // No ; after the block attached to control flow statements
}