1

如果我有一个使用正常标准的 jQuery 插件:

(function( $ ){
  var methods = {
    init : function( options ) {
      var defaults = {
      }
      var options =  $.extend(defaults, options);
      return this.each(function(){
        var returnValue = myUniversalFunction();
      });
    },
    test : function( options ) {
      var defaults = {
      }
      var options =  $.extend(defaults, options);
      return this.each(function(){
        var returnValue = myUniversalFunction();
      });
    }
  };
  $.fn.jPlugin = 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 );

我应该在哪里放置一个可以在 init 和 test 方法中访问但不能在插件本身之外使用的函数?

4

2 回答 2

5

将其放在第 2 行,紧随其后(function( $ ){,如下所示:

(function( $ ){
    var inner_function = function() {
        // ...
    };
    var methods = {
        // ...
    };
    $.fn.jPlugin = function( method ) {
        // ...
    };
})( jQuery );

该功能inner_function将在其内部的任何地方可用,(function($){ ... })(jQuery);但不在其外部。

于 2012-06-29T15:41:08.357 回答
0

就在顶部。该功能将适用于该范围内的所有内容。

(function( $ ){
    function myFunc() {
        // ...
    }
于 2012-06-29T15:43:15.220 回答