1

将原型插件移植到 jQuery。

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

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

2 回答 2

5

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

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

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

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

于 2012-08-19T13:23:50.510 回答
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);
于 2012-08-19T13:23:19.120 回答