You don't really need to do any of that, you should be able to just send in the function directly to document.ready
. You don't need to wrap it inside that anonymous function at all:
var LightBox = (function() {
var init = function(){
console.log('Lightbox Init');
}
$(document).ready(init);
})();
var CustomAnchors = (function(){
var init = function(){
console.log('CustomAnchors Init');
}
$(document).ready(init);
})();
An explanation of what you were trying to do:
As others have already said, since Lightbox
is just a straight up function (even though it's an IIFE), referring to this
inside it will just refer to the global object
. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
What you're trying to do is refer to this
as a custom object, but for that to work you have to instantiate an object. One method to do this is using the new
operator, as in new Lightbox()
(if Lightbox
is a function) or new function()
if you want to just create one instance from an anonymous function.
With your specific code it would be
var LightBox = new function() {
var me = this; // this will now refer to the instantly instantiated LightBox object
$(document).ready(function(){ me.init(); });
this.init = function(){ // You could use me.init here but I think it makes for harder-to-understand code
console.log('Lightbox Init');
}
};
var CustomAnchors = new function(){
var me = this; // and same here, for the CustomAnchors object
$(document).ready(function(){ me.init(); });
this.init = function(){
console.log('CustomAnchors Init');
}
};
But again, you don't really need to wrap it. I'm just explaining here what you were trying to do.