简体   繁体   English

有没有办法将一个jQuery函数包装到一个对象?

[英]Is there a way to wrap a jquery function to an object?

Is there anyway to limit the scope of a jquery function to an object other than using a main function: 无论如何,除了使用main函数之外,是否有将jquery函数的范围限制为对象的方法:

(function( $ ) {

    $.fn.myLib = function( funcName ) {

        if ( action === "func1") {
            // Open popup code.
        }

        if ( action === "func2" ) {
            // Close popup code.
        }

    };

}( jQuery ));

I'd like to do it so that I could call functions like this: 我想这样做,以便可以调用如下函数:

$(el).myLib.func1();
$(el).myLib.func2();

There's really not a lot of good reason to try to do this: 确实没有太多理由尝试这样做:

$(el).myLib.func1();

Because the this pointer when func1() executes will be myLib and you won't be able to access $(el) . 因为执行func1()时的this指针将是myLib ,因此您将无法访问$(el) So, it doesn't do you a whole lot of good unless all you want is static methods. 因此,除非您只想使用静态方法,否则它不会带来很多好处。 If that's what you actually want, then you can do this: 如果这是您真正想要的,则可以执行以下操作:

$.fn.myLib = {};
$.fn.myLib.func1 = function(...) {...};
$.fn.myLib.func2 = function(...) {...};

If you actually want to be able to have acceess to the jQuery object (which I presume), then stick to one level and use a name prefix which gives you about the same level of name conflict protection anyway. 如果您实际上希望能够访问jQuery对象(我认为是),那么请坚持使用一个级别并使用名称前缀,无论如何,它都会为您提供相同级别的名称冲突保护。

$.fn.myLibFunc1 = function(...) {...};
$.fn.myLibFunc2 = function(...) {...};

Then, you can do: 然后,您可以执行以下操作:

$(el).myLibFunc1();

And, the this pointer in myLibFunc1 will be the jQuery object that called it. 并且,myLibFunc1中的this指针将是调用它的jQuery对象。

(function( $ ) {
$.fn.myLib = function( funcName ) {
   var obj=new Object
   obj.func1=function () {alert('first')}
   obj.func2=function () {alert('second')}
   return obj

};
}( jQuery ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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