jQuery:如何使用文字对象方法中的方法获取全局变量

Ale*_*ill 1 javascript jquery scope

我正在将原型插件移植到jQuery。

插件使用禁止的方法来收集对象文字中的所有插件方法,然后像[object]一样调用它们。[方法]

我不明白的是,在所有这些方法中,都使用了似乎是全局的且未作为参数或属性传递的属性(在脚本的开头定义,即var x = 0,var y = 0等)。具体方法。

我将如何在jQuery中做到这一点,并且可能吗?

请参考以下代码中的“ var1”。它将在哪里设置,以便所有方法都可以访问它?

例:

;(function($){

    var methods = {
        init : function(options) {

            var config = {
            // default options...
            }

            // overide config
            var settings = $.extend(config, options);

            return this.each(function() {
                        // init code goes here...
            });
        },

        function1 : function() {
            function2();
        },

        function2 : function() {
                $(selector).css({
                  width : var1,
                });             
        },
    }

    $.fn.[PLUGINNAME] = 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 on jQuery.tooltip' );
      } 

    };

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

Chr*_*son 5

您需要在自调用函数内部但在任何其他函数外部声明变量。

(function($){
    // This variable will be available to all methods, 
    // but not outside the plugin
    var var1,
        methods = {
            init : function(options) {
                ...
            }
            ...
        };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用init方法为其设置适当的值,例如,如果它是初始化过程的一部分,而不仅仅是静态变量的话。

由于JavaScript使用函数声明变量范围,因此外部自调用函数将确保变量不会“泄漏”到全局范围,但是由于在任何内部函数之外都声明了该变量,因此该变量可用于插件中的所有功能。