jquery插件中的本地方法和命名空间

时间:2012-06-11 15:09:48

标签: jquery variables jquery-plugins plugins private-methods

我创建了一个插件,但想确定我对“本地”功能的处理方式。

以下是我所做的示意图:

(function($) {

 var methods = {
     init : function( options ) {

       // CODE ...

       // Call of a local function
       _test( this );

       // CODE .....

     },
     destroy : function( ) {       
         // CODE .....
        _test( this );
         // CODE .....
     }
  };

  function _test( container ) {
       // My code : example :
       $(container).append("<div id='myplugin'></div>");
  }

 $.fn.myplugin = 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.myplugin' );
    }    

  };

})(jQuery);

如您所见,我不直接在方法函数中插入代码,而是在其他_函数中插入代码。 _functions可以被视为插件的本地或私有功能吗?我没有成功在插件之外调用它们,所以在我看来它们可以被认为是私有函数......

我是否总是直接将我的代码放在methods对象的函数中? 如何声明将在多种方法中使用的函数?

命名空间怎么样?真的不明白。

谢谢!

1 个答案:

答案 0 :(得分:0)

由于您正在公开方法对象的所有方法,因此该对象的任何部分都不是私有的。但是,在另一个函数中声明的任何函数都限定为声明函数,因此如果您不以其他方式使函数可访问,那么它将是私有的。

相关问题