Search code examples
reactjstypescriptiife

How to apply IIFE in ReactJS + Typescript?


I would like to use IIFE in ReactJS + Typescript environment. So i rewrite this code with ReactJS + Typescript

IIFE

(function() { 
        //Constructor
        this.Radio = function(){ 

            var defaults = { 
                locale: "en-US", 
            }

        } 

        // Public Methods   
        Radio.prototype.load = function() { 

        } 
      }());

ReactJS + Typescript

    export default class Radio{
    options: any = { 
        locale: "en-US", 

    };
    constructor(props: any) {
        var defaults = { 
            locale: "en-US", 
        }

    }       

    // Public Methods   
    load = () => { 
    }
} 

What i try to achieve is when the bundle.js load from html page i'm able to instantiate by passing some value in like below

<script src="main.js"></script>
<body> 


    <div id="app"></div>

</body> 

<script>
    $(function() {
        var test = new Radio({   <----error on this line         
            locale: "en-US",            
        });
        test.load();
    });
</script>

But when i run above code i got this error Uncaught ReferenceError: Radio is not defined

Is that possible to implement IIFE like above?

Thanks


Solution

  • But when i run above code i got this error Uncaught ReferenceError: Radio is not defined

    If you want this old code to still work you need to put Radio on this just like old times. E.g.

     export default class Radio{
        options: any = { 
            locale: "en-US", 
    
        };
        constructor(props: any) {
            var defaults = { 
                locale: "en-US", 
            }
    
        }       
    
        // Public Methods   
        load = () => { 
        }
    } 
    
    // ADD
    (window as any).Radio = Radio;