0

I wrote a JS "plugin" using the following clever structure (which was not an idea of mine, I found googling around).

It basically functions as a class, with private methods, but don't have to use the private keyword notation (which is not fully supported even in modern browsers), or the class notation.

var myPlugin = (function () {

    'use strict';

    /**/
    var Constructor = function (options) {

        var publicAPIs = {};

        //private method
        function myFunction() { }       

        //public method
        publicAPIs.myFunction2 = function () {
            return 1;
        }

        return publicAPIs;
    };

    return Constructor;
})();

Now the problem is I don't fully get how this works. It is used in the following way :

var myPlugin = new myPlugin({
        selector: '#selector-test'
});
myPlugin.myFunction2();

I guess the "new" keyword will use the outer function which returns the Constructor (which returns the publicApi object). Is that correct ? Also, I guess instantiating an Object in this way will "copy" all the Constructor's functions within each instantiated Object (which is not a problem in my case, since I'm using just a single Object).

Another question I have is the following : Would it be possible in JS to call this plugin directly on an element instead of passing the selector (or directly the element) in the arguments ? Basically something like JQuery plugins work. I'd like to do something like the following :

var myElement = document.querySelector('#id');
myElement.myPlugin(options);

Thanks.

Nite
  • 67
  • 1
  • 6
  • 3
    See [What is the `(function() { })()` construct in JavaScript?](https://stackoverflow.com/q/8228281/4642212). It’s an IIFE (immediately invoked function expression) which returns the constructor. There isn’t that much of a point doing it here — it just has `'use strict';` there, so the constructor is in strict mode, but IIFEs are really useful to hide variables from outer scopes there. – Sebastian Simon Feb 25 '21 at 00:33
  • 3
    To answer your second question: no. `myPlugin` is a function available in the scope that calls `new myPlugin`; it’s not an `Element` prototype method, i.e. it doesn’t exist on `Element.prototype.myPlugin`. For that to work, see [Invoke a custom method on a DOM element](https://stackoverflow.com/a/30906233/4642212). – Sebastian Simon Feb 25 '21 at 00:35
  • @SebastianSimon Thanks for the help ! Again regarding the same example I posted, would it be possible to assign myFunction() (the private one), to the prototype of myPlugin ? – Nite Feb 27 '21 at 00:21
  • To answer my own question, maybe I should look at the Revealing Prototype Pattern – Nite Feb 27 '21 at 01:20

0 Answers0