0

I "borrowed" this snippet from another site, and I've realized that it does not work when I try to use it. What is wrong with it?

var LessonsCustomControl = (function LessonsCustomControl_constructor(){

    var LessonTypes=[], LessonInterfaces={}, LessonsContent={};
    
    LessonInterfaces.ListQuiz1 = (function(typeClass){
        ...
    }

    function initListQuiz1(){
        LessonInterfaces.ListQuiz1('FITBPickOption').init();
    }

})();

In my code, when I try to call initListQuiz1(), I am getting nothing, i.e. LessonsCustomControl is undefined. Need some help in rewriting this in valid javascript or jquery.

Lawrence DeSouza
  • 984
  • 5
  • 16
  • 34
  • Does this answer your question? [Why does this JavaScript code print "undefined" on the console?](https://stackoverflow.com/questions/10263190/why-does-this-javascript-code-print-undefined-on-the-console) – vanowm Jul 11 '21 at 20:39
  • `LessonsCustomControl_constructor` doesn't return anything, therefore you can't access anything that is generated inside that function, including `ListQuiz1` – vanowm Jul 11 '21 at 20:40
  • Thanks, I didn't even realize that for a whole week, but it is obvious. I have re-written everything without the need for returning - this aspect was not suited for my purpose. – Lawrence DeSouza Jul 11 '21 at 21:21

1 Answers1

1

The code you borrowed features encapsulation with an IIFE.

In order to use some functions from outside it, you have to return them:

var LessonsCustomControl = (function LessonsCustomControl_constructor(){

    var LessonTypes=[], LessonInterfaces={}, LessonsContent={};
    
    LessonInterfaces.ListQuiz1 = (function(typeClass){
        ...
    }

    function initListQuiz1(){
        LessonInterfaces.ListQuiz1('FITBPickOption').init();
    }

    return {
        initListQuiz1,
        // Other functions you need to "export"
    }

})();

Then call:

LessonsCustomControl.initListQuiz1();
Guerric P
  • 30,447
  • 6
  • 48
  • 86