jQuery插件从方法返回值,但仍保留可链接性

jQuery插件从方法返回值,但仍保留可链接性,jquery,jquery-plugins,return-value,chaining,Jquery,Jquery Plugins,Return Value,Chaining,我目前正在重新设计我的个人jQuery插件的起点,但我遇到了一个小而恼人的问题。如果调用公共方法,它将返回调用它的对象的值,而不是值 以下是我的实际出发点: ;(function($, window, document, undefined) { 'use strict'; var pluginName = 'defaultPluginName', defaults = { foo: 'foo', bar: 'ba

我目前正在重新设计我的个人jQuery插件的起点,但我遇到了一个小而恼人的问题。如果调用公共方法,它将返回调用它的对象的值,而不是值

以下是我的实际出发点:

;(function($, window, document, undefined) {
    'use strict';

    var pluginName = 'defaultPluginName',
        defaults = {
            foo: 'foo',
            bar: 'bar'
        },
        settingsKey = pluginName + '-settings';


    var init = function(options) {

        var elem = this,
            $elem = $(this),
            settings = $.extend({}, defaults, options);

        $elem.data(settingsKey, settings);

    };


    var callMethod = function(method, options) {
        var methodFn = $[pluginName].addMethod[method],
            args = Array.prototype.slice.call(arguments);
        if (methodFn) {
            this.each(function() {
                var opts = args.slice(1),
                    settings = $(this).data(settingsKey);
                opts.unshift(settings);
                methodFn.apply(this, opts);
            });
        }
    };

    $[pluginName] = {
        settingsKey: settingsKey,
        addMethod: {
            option: function(settings, key, val) {
                if (val) {
                    settings[key] = val;
                } else if (key) {
                    return settings[key]; // returns the value from settings
                }
            }
        }
    };

    $.fn[pluginName] = function(options) {
        if (typeof options === 'string') {
            callMethod.apply(this, arguments);
        } else {
            init.call(this, options);
        }
        return this;
    };

}(window.jQuery || window.Zepto, window, document));
但是,我初始化插件并调用一个方法

$('div').defaultPluginName();
console.log($('div').defaultPluginName('option', 'foo'));
它返回:
[,prevObject:jQuery.fn.jQuery.init[1],上下文:#文档,选择器:“div”]
,而不是
'foo'
作为(注释所在的位置)例外


所以问题是,是否有可能从公共方法返回值,并且仍然保持可链接性?如果你有时间和乐趣帮助我,我很乐意举一些例子;)

我自己解决了:

$.fn[pluginName] = function(options) {
    var returns;
    if (typeof options === 'string') {
        var args = arguments,
            methodFn = $[pluginName].addMethod[args[0]];

        if (methodFn) {
            this.each(function() {
                var opts = Array.prototype.slice.call(args, 1),
                    settings = $.data(this, settingsKey);
                opts.unshift(settings);
                returns = methodFn.apply(this, opts);
            });
        }
    } else {
        new Plugin(this, options).init();
    }
   return returns !== undefined ? returns : this;
};