There was a question about the correct approach to creating a plugin on js.

An example of work on Plunker , as well as github code.

The essence of the plugin:

  • There are images on the page, when clicking on them, a modal window opens;
  • In this modal window there is a Slider and Previews with these images, which we can scroll through, switch, etc .;
  • in the slider we can transfer the parameters for displaying the number of previews and the ability to turn them off;
  • on one page we can use the plugin several times.

Problem : when used two or more times, the plugin breaks down and displays only the last gallery.

(function() { let gallery_1 = new SkySlider('.first-gallery'); let gallery_2 = new SkySlider('#second-gallery', { showThumbnails: true, thumbnailsItemCount: 6, }); })(); 
  • 2
    because you need to figure out how this works, and not to try crutches with one local variable for all instances - Grundy
  • one
    You have _ "global" for all sliders, so when creating a new slider, all old ones in _ change to this new slider (all due to the closure) - ThisMan
  • one
    Why not make the other functions using SkySlider ? - ThisMan
  • one
    Designed as the answer - ThisMan
  • one
    Learn more about losing and saving context - Grundy

1 answer 1

Instead of storing this in a closure, like you did

 (function() { // for `this` let _; function SkySlider(selector = null, options = null) { _ = this; } // остальные функции использующие _ в качестве this })() 

It is possible to place all auxiliary functions in the prototype of the SkySlider function SkySlider

 (function() { function SkySlider(selector = null, options = null) {} SkySlider.prototype.init = function () {} SkySlider.prototype.otherMethod = function () {} // либо по другому делаем функцию доступной из вне window.SkySlider = SkySlider })() 

In such methods, this will refer to the current instance of the class and not overwrite any global variable.

  • bad example with prototypes :-) SkySlider will be visible only inside this IIFE - Grundy
  • @Grundy, it also has the line window.SkySlider = SkySlider - ThisMan
  • Yeah, and you didn't have it :) - Grundy
  • @Grundy, it's just not really related to the question, I thought that inserting the rest of the code is not necessary) - ThisMan