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

时间:2012-08-19 13:18:12

标签: 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);

2 个答案:

答案 0 :(得分:4)

你需要在自我唤起函数中声明变量,但在任何其他函数之外。

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

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

由于JavaScript使用函数来声明变量作用域,因此外部自我唤起函数将确保变量不会“泄漏”到全局作用域,但由于它是在任何内部函数之外声明的,因此它将可用于插件中的所有功能。

答案 1 :(得分:2)

如果您在其他所有内容之前在最顶层的函数中定义它,则所有其他方法都可以访问它:

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