2013-05-13 56 views
1

你好,我刚开始进入JQuery插件,但我有一些理解命名空间的问题。JQuery和原型命名空间

鉴于下面的例子,当我进入“提交”功能,我如何获得提交功能内的原型实例?像“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)); 
+0

你在说什么“实例”? – Ohgodwhy 2013-05-13 17:35:56

回答

2

其实,有一些误解的概念在这里:

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

  2. “this”是包含当前函数执行上下文的keword,并且可以根据修改如何调用给定的函数

  3. 我建议您阅读一些有关jQuery插件开发这里:http://learn.jquery.com/plugins/

这就是说,我可以提出一个典型的方法:

  1. 有作为的性质插件的所有方法一个“方法”对象(您当前的PluginPrototype

  2. Im $ .fn.pluginName函数内部的plement logic来处理不同的执行请求。

    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"); 
        } 
    }); 
    

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

    b。插件方法通过$(“...”)调用。plugin(“method name”,argument1,argument2,...);

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

    methods.methodName.call(this, argument1, argument2); 
    

希望这有助于你。

+0

相当体面的答案“这个”一个! – 2013-05-13 19:53:01

+0

Eheh是的,我的英语很糟糕。另外,我有点新回答问题..希望我会好起来;) – sixFingers 2013-05-13 20:23:46

+0

我只是改变了删除“希望这可以帮助你。”作为多余的文字。 – 2013-05-13 20:35:14