JQuery和原型名称空间

时间:2013-05-13 17:34:12

标签: jquery prototype

您好我刚刚开始使用JQuery插件,但我在理解命名空间时遇到了一些问题。

鉴于以下示例,当我输入“submit”函数时,如何在submit函数中获取原型实例?比如“var self = this;”在另一个功能?在该方法中,这是指表单元素。

(function ($, window, document, undefined) {
    var PluginPrototype = {
        init: function (options, element) {
            var self = this;

            $(element).find('form').submit(self.submit);
            self.otherMethod();
        },

        submit: function(){
            var self = this; // the form element
        },

        otherMethod: function () {
            var self = this; // the prototype
        },
    }

    $.fn.pluginname = function (options) {
        return this.each(function () {
            var plugin = Object.create(PluginPrototype);
            plugin.init(options, this);

            $.data(this, 'pluginname', comment);
            // Get it by 
            // $.data($(select)[0], 'comment');
        });
    };

    $.fn.pluginname.Settings = {

    };
}(jQuery, window, document));

1 个答案:

答案 0 :(得分:2)

实际上,这里有一些被误解的概念:

  1. 您的案例中没有“原型实例”。当Prototype用作构造函数时,Prototype是函数的属性。在你的情况下,PluginPrototype只是一个普通的对象,它的原型是Object.prototype。

  2. “this”是一个包含当前函数执行上下文的关键字,可以根据 调用给定函数进行修改。

  3. 我建议在这里阅读一些关于jQuery插件开发的内容:http://learn.jquery.com/plugins/

  4. 那就是说,我可以建议一种典型的方法:

    1. 将插件的所有方法都作为“方法”对象的属性(您当前的 PluginPrototype

    2. 在$ .fn.pluginName函数中实现逻辑以处理不同的执行请求。

      return this.each(function() {
          if (methods[method]) {
              return methods[method].apply(this, Array.prototype.slice.call(parameters, 1));
          } else if ( typeof method === "object" || ! method ) {
              return methods.init.apply(this, parameters);
          } else {
              $.error("Method "+method+"does not exist on my wonderful plugin");
          }
      });
      

      一个。插件初始化通过$(“...”)。plugin({option:value,...});

      调用

      湾插件方法通过$(“...”)。plugin(“方法名称”,参数1,参数2,...)调用;

    3. 将使用“this”调用所有方法,指向当前jQuery包装的dom元素;所以,要从另一个方法中调用一个方法,你将使用:

      methods.methodName.call(this, argument1, argument2);
      
    4. 希望这会对你有所帮助。

相关问题