1

我正在编写一个 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 个值 - 我应该创建某种全局变量吗?做这个的最好方式是什么?

4

3 回答 3

1

Variables are visible in the function where they are declared (i.e. the function where their var statement appears) and in any functions that are declared within that function.

Here's an example:

(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

You should never use global variables (i.e. variables that aren't declared with the var statement inside a function). These are visible to all other code in your document. However, as long as you enclose everything in a function and always use var you're safe.

于 2012-09-04T10:56:50.633 回答
1

这是最好的开始:jQuery Boilerplate

于 2012-09-04T11:10:58.020 回答
0

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

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

于 2012-09-04T10:55:58.583 回答