I have the following script:
(function () {
var Module = (function () {
var fctToCall = function () {
alert('Foo');
};
return {
fctToCall: fctToCall
};
})();
var Module2 = (function () {
var init = function () {
var str = 'fctToCall';
Module.str(); // here
};
return {
init: init
};
})();
})();
So I want to call this fctToCall
method by its name - how can I do that? So far I know 3 methods:
How can I solve this?
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
So, it is possible to store a named function inside a variable, but we still can only call the function by the variable name.
Syntax. Users can follow the below syntax to write the expression for the arrow function. const variable = ( … parameters ) => { // function body } Variable( parameters ); // invoke the arrow function.
It will no longer refer to it's original global built-in function, even though you assign a new value at the end of the function. You must be getting this error too.
To call function use
Module[str]();
As Module
is an object, you can access the dynamic properties and methods of it by using the bracket notation.
(function() {
var Module = (function() {
var fctToCall = function() {
console.log('Foo');
};
return {
fctToCall: fctToCall
};
})();
var Module2 = (function() {
var init = function() {
var str = 'fctToCall';
// Call as
Module[str]();
};
return {
init: init
};
})();
Module2.init();
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With