构造jQuery插件

Structring jQuery plugins

本文关键字:插件 jQuery 构造      更新时间:2023-09-26

我正在写一个jQuery插件,经常被某些函数的范围弄糊涂(使用jS时是传统的)。

一个简短的例子应该会有所帮助:

(function ( $ ) {
    var methods = {
        init: function ( options ) {
            var settings = $.extend ({
                a: 100,
                b: 200
            }, options);
            return this.each(function(){
                var $this = $(this);
                var return_value = $this.plugintest("method_1", settings);
                $this.plugintest("method_2", settings, return_value);
            });
        },
        method_1 : function ( settings ) {
            var method_1_value_1 = settings.a * 10,
                method_1_value_2 = settings.a * 20;
            return method_1_value_1;
        },
        method_2 : function ( settings, old_return_value ) {
            // WHAT IF I WANT BOTH method_1_value_1 AND method_1_value_2 in here?
        }
    };
    $.fn.plugintest = function (method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call ( arguments, 1 ) );
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' + method + ' does not exist in jQuery.robottest' );
        }
    };
}) (jQuery);

参见方法_2。我想访问我在method_1中创建的值,但我只能返回1个值——我应该创建某种全局变量吗?做到这一点的"最佳"方法是什么?

变量在声明它们的函数中(即出现其var语句的函数)以及在该函数中声明的任何函数中都是可见的。

这里有一个例子:

(function () {
    var foo;
    // foo is visible here, bar is not
    // declare variables that should be visible to your whole plugin here
    var methods = {
        a: function () {
            var bar;
            // foo and bar are both visible here
        },
        b: function () {
            // foo is visible here, bar is not
        }
    };
}());
// neither foo nor bar are visible here

您永远不应该使用全局变量(即未在函数内用var语句声明的变量)。这些代码对文档中的所有其他代码都可见。但是,只要您将所有内容都包含在function中并始终使用var,您就安全了。

这是最好的开始:jQuery Boilerplate

函数中定义的变量将在函数范围内。在函数之前声明的任何内容都将在父作用域中。父作用域将由父作用域中的函数可见,具体取决于变量声明。

所以,如果您在父函数中声明变量,而不在内部函数中再次声明它们,将导致从内部函数访问这两个变量。