简体   繁体   中英

Importance of return this; in plugin function?

I am learning Jquery and I am trying to get how to make a plugin.

$.fn.myfun = function(options) {
        if (typeof options === 'string') {
            callOption.apply(this, arguments);
        } else {
            initElements.call(this, options);
        }
        return this;
    };

I am not able to understand why there is a statement return this ? Why do we return it?

This is so you or the end user of your plugin can chain other jQuery methods after calling your plugin. For example:

$('.foo').myFun().slideToggle();

Returning this returns a jQuery object in this case, maintaining access to all the methods jQuery has.

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