JavaScript命名空间与jQuery

Tom*_*ker 6 javascript jquery

如何管理自定义JavaScript库的命名空间依赖于jQuery?

您是否创建了自己的命名空间,foo并在那里添加对象?例如foo.myClass, foo.myFunction

或者你将对象添加到jQuery的命名空间?例如jQuery.myClass, jQuery.myFunction

哪种更常见的做法为什么?

Dav*_*nco 7

本文讨论以极其详细的方式编写jQuery插件/库.

什么不该做:

(function( $ ){

  $.fn.tooltip = function( options ) { // THIS };
  $.fn.tooltipShow = function( ) { // IS   };
  $.fn.tooltipHide = function( ) { // BAD  };
  $.fn.tooltipUpdate = function( content ) { // !!!  };

})( jQuery );
Run Code Online (Sandbox Code Playgroud)

该怎么办:

(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 );
Run Code Online (Sandbox Code Playgroud)

去年我还写了一篇关于JavaScript中命名空间的各种方法的博客文章(非jQuery相关).


use*_*716 4

这取决于图书馆做什么。

  • 如果您要扩展 jQuery 对象实例的功能,您可以使用@David Titarenco他的回答jQuery.fn中很好地描述的内容。

  • 如果您创建的实用程序旨在被视为对 中提供的实用程序的补充window.jQuery,那么我认为使用该命名空间不会有问题(只要您小心命名)。

  • 如果它确实是它自己的独立库,并不意味着被视为 jQuery 的扩展,而是依赖于 jQuery 的功能,那么一定要使用您自己的命名空间。