如何使函数在整个 jQuery 插件及其所有内部方法中可用

How can I make a function available throughout a jQuery plugin and all its internal methods?

本文关键字:内部 方法 函数 何使 插件 jQuery      更新时间:2023-09-26

如果我有一个使用正常标准的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 和测试方法中访问但不能将其提供给插件本身之外的函数?

把它放在第 2 行,紧跟在 (function( $ ){ 之后,像这样:

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

该函数inner_function将在(function($){ ... })(jQuery);内的任何位置可用,但在外部不可用。

就在顶部。该函数将可用于该范围内的所有内容。

(function( $ ){
    function myFunc() {
        // ...
    }