如何管理依赖于jQuery自定义JavaScript库的命名空间?
您是否创建了自己的名称空间,比如foo,并在其中添加了对象?例如foo.myClass, foo.myFunction
还是将对象添加到jQuery的名称空间?例如jQuery.myClass, jQuery.myFunction
哪种做法更常见?为什么?
发布于 2011-01-30 03:26:39
这将取决于库的功能。
jQuery.fn,正如@David Titarenco在his answer中所描述的那样。window.jQuery中提供的实用程序的补充,那么我认为使用该命名空间没有问题(只要您注意命名)。发布于 2011-01-30 03:16:59
This article详细讨论了如何编写jQuery插件/库。
不能做的事情:
(function( $ ){
$.fn.tooltip = function( options ) { // THIS };
$.fn.tooltipShow = function( ) { // IS };
$.fn.tooltipHide = function( ) { // BAD };
$.fn.tooltipUpdate = function( content ) { // !!! };
})( jQuery );该怎么做:
(function( $ ){
var methods = {
init : function( options ) { // THIS },
show : function( ) { // IS },
hide : function( ) { // GOOD },
update : function( content ) { // !!! }
};
$.fn.tooltip = function( method ) {
// Method calling logic
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 );去年,我还写了一篇关于JavaScript (与jQuery无关)中命名空间的各种方法的blog post。
https://stackoverflow.com/questions/4838876
复制相似问题