Creating a jQuery plugin: explanation for the keyword "this"?

I have been coding jQuery for about two years now, but I have never done this in a plugin. I am trying to change that. I found several sites that explain how to create a plugin, and I understand the basics.

The part that I do not understand is the use of the keyword this. Here is a simple plugin example:

(function($){
  $.fn.myPlugin = function(options)
  {
    // Do whatever
    return this.each(function(){
      element = $(this);
    });
  }
  $.fn.myPlugin.init = function()
  {
    // Initiate plugin
  }
})(jQuery);

On the fifth line of my code I have this.each. In this case, the keyword thisapplies to all elements of the selector. The next line uses $(this)which is the current element, just as if I were doing it in .click(function(){$(this).hide();}).

, OO, this . $.fn.myPlugin $.fn.myPlugin.init(), , - this.init(), , , .

, , , this.myVariable = "my value".

, - , , jQuery, , ! , , , .;)

+3
1

.each(), this jQuery, DOM.

, , . $.fn.myPlugin.

this.myPlugin.init();

:

$(this).myPlugin.init();

:

$.fn.myPlugin.init();
+2

Source: https://habr.com/ru/post/1761943/


All Articles