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

jQuery: How to get global variables using methods in literal object approach

本文关键字:方法 获取 全局变量 对象 何使用 文字 jQuery      更新时间:2023-09-26

我将原型插件移植到 jQuery。

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

我不明白的是,在任何这些方法中,都使用了属性(在脚本的乞求处定义,即 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);

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

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

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

由于 JavaScript 使用函数来声明变量范围,

因此外部自唤函数将确保变量不会"泄漏"到全局范围,但由于它是在任何内部函数之外声明的,因此它将可用于插件中的所有函数。

如果你在其他

所有事情之前在最顶层的函数中定义它,它将可以通过所有其他方法访问:

(function($){
    var var1 = "some value";
    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.slideshow = 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);