You get a bonus - 1 coin for daily activity. Now you have 1 coin

js call function by name as string

Lecture



In JavaScript, you can call a function by its name, even if the name is represented as a string. There are a few ways to achieve this, but one common method is by using the global object (e.g., window in browsers or global in Node.js). Here's how you can do it:

Method 1: Using the global object (for functions defined in the global scope):


 
javascript
// Assuming you have a function named 'myFunction' in the global scope
function myFunction() {
console.log("Hello, I'm the function!");
}
const functionName = "myFunction";
// Call the function by its name as a string using the global object
window[functionName](); // For browsers // OR
global[functionName](); // For Node.js

Method 2: Using an object (for functions defined within an object):


 
javascript
const myObject = {
someFunction: function () {
console.log("Hello, I'm the function inside an object!");
},
};
const functionName = "someFunction";
// Call the function by its name as a string using the object
myObject[functionName]();

Method 3: Using eval() (not recommended due to security risks):


 
javascript
function myFunction() {
console.log("Hello, I'm the function!");
}
const functionName = "myFunction";
// Call the function by its name as a string using eval() - not recommended!
eval(functionName + "()");

Note: While eval() can be used to achieve this, it is generally not recommended due to potential security vulnerabilities and performance issues. It's best to use the first or second method, depending on the scope of the function you want to call.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone