I am kind of a OO js noobie and am trying to create a new Javascript library the correct way but am struggling to understand how best to do this and make it work properly. I would like my library to self invoked so that an object ABC is instantiated as soon as the js library file is included in the html. However, then users should be able to call methods on that object in the html page.
I've tried a few different versions of the below code, but can't seem to get the prototype method for declaring methods to work properly. On my HTML page, I can call ABC.alert(); and it properly executes the alert message. However, when I try to call ABC.alert2(); which is using prototype inheritance which I understand is more memory efficient than just declaring methods right inside the object constructor, I can't seem to get that to work. I keep getting ABC.alert2 is not a function. I do see that my ABC object does have the proto property, but I can't seem to figure out how to define methods properly using prototype. Is it because I'm using a self invoked function? Should I not use a self invoked function and instead at the bottom of my library just create a new instance of my object manually with var ABC = new defineABC(); line?
Also copied below:
(function (window) {
'use strict';
function defineABC() {
var ABC = {};
ABC.alert = function() {
alert("hello this is working");
};
ABC.prototype.alert2 = function() {
alert("hello prototype is working inside constructor");
};
return ABC;
}
defineABC.prototype.alert3 = function() {
alert("hello prototype is working outside constructor");
};
if (typeof(ABC) === 'undefined') {
window.ABC = defineABC();
}
})(window);
ABC.alert(); //successful
ABC.alert2(); //fails
ABC.alert3(); //fails