【问题标题】:How to make a public method in jQuery Plugin如何在 jQuery 插件中创建公共方法
【发布时间】:2012-08-17 01:35:27
【问题描述】:

我一直在使用下面的样板进行 jQuery 插件开发,效果很好。但我不确定公开“方法”的最佳方式。

           ;(function ( $, window, undefined ) {

              var pluginName = 'defaultPluginName',
                  document = window.document,
                  defaults = {
                    propertyName: "value"
                  };

              function Plugin( element, options ) {
                this.element = element;

                this.options = $.extend( {}, defaults, options) ;

                this._defaults = defaults;
                this._name = pluginName;

                this.init();
              }

              Plugin.prototype.init = function () {

              };

              $.fn[pluginName] = function ( options ) {
                return this.each(function () {
                  if (!$.data(this, 'plugin_' + pluginName)) {
                    $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
                  }
                });
              }

            }(jQuery, window));

谢谢

【问题讨论】:

  • window.fnName = function(){};
  • 我并没有尝试创建全局函数。我想正确地确定方法的范围。
  • JavaScript 没有属性/方法可见性的概念。范围仅根据全局范围/函数范围/lambda-范围进行评估。

标签: javascript jquery jquery-plugins methods public


【解决方案1】:

只有函数可以是私有/本地的,不能是 jQuery 插件。

如果您正在使用 jQuery 并尝试在 jQuery 中添加自己的(自定义)函数,有一个最好的方法 jQuery.fn.yourFunctionname = function(){},因为 jQuery 已经在公共范围内,所以 jQuery.fn.yourFunctionname 是一个公共范围(无论您在哪里定义您的插件,将可供全球使用)。

window.jQuery = jQuery;


$.fn.pluginName = function ( options ) {

    return this.each(function () {
    // code goes here
    });
}

【讨论】: