根据jQuery插件创作页面(http://docs.jquery.com/Plugins/Authoring),最好不要混淆jQuery和jQuery.fn命名空间。他们建议这种方法:
(function( $ ){ var methods = { init : function(options) { }, show : function( ) { },// IS hide : function( ) { },// GOOD update : function( content ) { }// !!! }; $.fn.tooltip = function(methodOrOptions) { if ( methods[methodOrOptions] ) { return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) { // Default to "init" return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' ); } };})( jQuery );基本上,您将函数存储在数组中(作用域为包装函数),并检查输入的参数是否为字符串,如果参数为对象(或为null),则返回默认方法(此处为“ init”)。
然后您可以像这样调用方法…
$('div').tooltip(); // calls the init method$('div').tooltip({ // calls the init method foo : 'bar'});$('div').tooltip('hide'); // calls the hide method$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update methodJavascripts“ arguments”变量是所有传递的参数的数组,因此它可以与任意长度的函数参数一起使用。



