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);

method_2を参照してください。method_1で作成した値にアクセスしたいのですが、返すことができるのは1つの値だけです。ある種のグローバル変数を作成する必要がありますか?これを行うための「最良の」方法は何ですか?

4

3 に答える 3

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ただし、すべてをaで囲み、常に使用する限り、var安全です。

于 2012-09-04T10:56:50.633 に答える
1

これが最良のスタートです:jQueryボイラープレート

于 2012-09-04T11:10:58.020 に答える
0

関数内で定義された変数は、関数スコープに含まれます。関数の前に以前に宣言されたものはすべて、親スコープに含まれます。変数宣言に応じて、親スコープは親内の関数によって表示されます。

したがって、親内で変数を宣言し、内部関数で再度宣言しないことにより、内部関数から両方の変数にアクセスできるようになります。

于 2012-09-04T10:55:58.583 に答える