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.