不带括号调用jquery扩展

Fre*_*kyB 1 javascript jquery

我有这样写的jQuery扩展:

$.fn.GetBootstrapDeviceSize = function() {
var cMobileSize = $('#users-device-size').find('div:visible').first().attr('id');
return (cMobileSize === "xs" || cMobileSize === "sm");
Run Code Online (Sandbox Code Playgroud)

}

为了调用它,我使用:

$().GetBootstrapDeviceSize()
Run Code Online (Sandbox Code Playgroud)

有没有办法像这样调用这个相同的函数:

$.GetBootstrapDeviceSize()
Run Code Online (Sandbox Code Playgroud)

或者甚至可能是这样的:

$.GetBootstrapDeviceSize
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

有没有办法像这样调用这个相同的函数:

$.GetBootstrapDeviceSize()
Run Code Online (Sandbox Code Playgroud)

是的,穿上它$,而不是$.fn:

    $.GetBootstrapDeviceSize = function() {
 // ^^
    var cMobileSize = $('#users-device-size').find('div:visible').first().attr('id');
    return (cMobileSize === "xs" || cMobileSize === "sm");
    }
Run Code Online (Sandbox Code Playgroud)

或者甚至可能是这样的:

$.GetBootstrapDeviceSize
Run Code Online (Sandbox Code Playgroud)

是的,但它可能不是最好的做法.你可以通过在以下方面为该属性创建一个getter来实现$:

Object.defineProperty($, "GetBootstrapDeviceSize", {
    get: function() {
        var cMobileSize = $('#users-device-size').find('div:visible').first().attr('id');
        return (cMobileSize === "xs" || cMobileSize === "sm");
    }
});
Run Code Online (Sandbox Code Playgroud)

然后访问$.GetBootstrapDeviceSize将运行该函数并为您提供返回值.我可能只是称之为BootstrapDeviceSize,因为你正在访问它,好像它不是一个方法,所以名词而不是动词是有道理的.