Skip to content Skip to sidebar Skip to footer

Calling Function Defined In An Iife Function From Html

I have a IIFE function in a file called test.js i.e. (function mainIIFE() { 'use strict'; var print_name = function(first, last) { console.log(first + ' ' + last);

Solution 1:

Since you declare print_name with var, its scope is local to the IIFE, so you can't call it from outside there. You need to assign to window.print_name to make it global.

(functionmainIIFE() {
    "use strict";
    window.print_name = function(first, last) {
        console.log(first + " " + last);
    };
}());

It's also not clear why you're using new to call the function, since it doesn't fill in an object.

Solution 2:

You can return the function and store it in a variable. This is essentially the same as assigning it to window.print_name inside the IIFE since the new variable will be in global namespce

var print_name = (functionmainIIFE() {
    "use strict";
    var print_name = function(first, last) {
        console.log(first + " " + last);
    };
    return print_name;
}());

print_name('Foo','Bar')

Post a Comment for "Calling Function Defined In An Iife Function From Html"