使用方法扩展jQuery,但返回该方法而不是jQuery对象

时间:2017-02-23 12:34:11

标签: javascript jquery

我想这不是特定于jQuery的,但它参与了我的示例..所以我以这种方式扩展了jQuery:

$.fn.extend({
    MyMethod : function(options = {}){
        return $(this).each(function(){
            // Code here
        });
    }
});

但是..如果不是返回$(this)jquery对象,我想返回MyMethod方法/类..我想我可以做类似的事情:

return arguments.callee

但不幸的是,它既不适用于现代的javascript,也不适用于严格的模式。

我可以采用另一种方式返回该方法吗?

1 个答案:

答案 0 :(得分:0)

这似乎很奇怪。 :-)但是只需给函数一个名称,使该名称在函数内的范围内;您可以使用它来返回它:

$.fn.extend({
    MyMethod : function MyMethod(options = {}){
    // Name ------------^
        $(this).each(function(){
            // Code here
        });
        return MyMethod; // <== Return it
    }
});

过时的浏览器存在该结构的问题(称为命名函数表达式),但现代浏览器没有。

或者就此而言,您可以使用已经可以通过$.fn访问的引用:

$.fn.extend({
    MyMethod : function(options = {}){
        $(this).each(function(){
            // Code here
        });
        return $.fn.MyMethod; // <== Return it
    }
});