简体   繁体   中英

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:

(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) . 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.

$.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.

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

};
}( jQuery ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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