在JQuery扩展函数中,如何访问实例选项?

在JQuery扩展函数中,如何访问实例选项?,jquery,jquery-plugins,Jquery,Jquery Plugins,我有一个带有函数的JQuery扩展,我不知道如何访问实例的选项: (function ($) { $.fn.MyExtension= function (methodOrOptions) { if (methods[methodOrOptions]) { return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));

我有一个带有函数的JQuery扩展,我不知道如何访问实例的选项:

    (function ($) {

    $.fn.MyExtension= function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
            // Default to "init"
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + methodOrOptions + ' does not exist on jQuery.MyExtension');
        }
    };

    var methods = {
        init: function (options) {
            var defaults = {
                testOption: "test"
            };
            options = $.extend(defaults, options);

            return this.each(function () {
                 // Code logic goes here
            }

        MyFunction: function () {
            var optionVal = options.testOption;
        }
    };

})(jQuery);

因此,当我调用MyFunction时,这段代码会抛出一个错误,因为它不知道“选项”是什么。

所以,我相信这只是一个简单的范围问题。您可以将对象选项传递到
init
,但它是该函数的本地选项。你需要把它放在对象上,这样你的另一个函数,
MyFunction
就有了它的作用域

var methods = {
    init: function (options) {
        var defaults = {
            testOption: "test"
        };
        this.currentOptions = $.extend(defaults, options);

        return this.each(function () {
             // Code logic goes here
        }

    MyFunction: function () {
        var optionVal = this.currentOptions.testOption;
    }
};

将其存储在元素的数据对象上

(function ($) {

    $.fn.MyExtension = function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
            // Default to "init"
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + methodOrOptions + ' does not exist on jQuery.MyExtension');
        }
    };

    var methods = {
        init: function (options) {
            var defaults = {
                testOption: "test"
            };
            return this.each(function () {
                var $this = $(this);
                $this.data("MyExtension",$.extend(defaults, options));
                // Code logic goes here
            });
        },
        MyFunction: function () {
            var optionVal = this.data("MyExtension").testOption;
            console.log(optionVal);
        }
    };

})(jQuery);

$("body").MyExtension({testOption: "foobar!"}).MyExtension("MyFunction");