Sometimes you need to make certain variables and functions of a module accessible from the outside. Let's see how it's done. Let's say we have the following module:
;(function() {
let str = 'a module variable';
function func() {
alert('a module function');
}
})();
Let's export our function func
. To do this, we write
it into the property of the window
object embedded
in the browser:
;(function() {
let str = 'a module variable';
function func() {
alert('a module function');
}
window.func = func;
})();
Now we can call our function from outside the module:
;(function() {
let str = 'a module variable';
function func() {
alert('a module function');
}
window.func = func;
})();
window.func(); // shows 'a module function'
In this case, it is not necessary to call the function as
a property of the window
object:
;(function() {
let str = 'a module variable';
function func() {
alert('a module function');
}
window.func = func;
})();
func(); // shows 'a module function'
Given the following module:
;(function() {
let str1 = 'a module variable';
let str2 = 'a module variable';
let str3 = 'a module variable';
function func1() {
alert('a module function');
}
function func2() {
alert('a module function');
}
function func3() {
alert('a module function');
}
})();
Export one of the variables and any two functions to the outside.