Dynamically call a method
Here is the updated code with the commented code removed:
const method_name = {"key":"getCountry","key1":"getCountry1"};
const methods = {
getCountry1: () => {
console.log("I am getCountry1");
}
};
methods[method_name.key1]();
// Check if the method exists
if (methods[method_name.key2]) {
methods[method_name.key2]();
} else {
console.error(`Method ${method_name} does not exist`);
}
If you want to dynamically call a method in JavaScript based on a variable that contains the method name, you can use the square bracket notation to access the method. Here's an example based on your code:
const method_name = "getCountry";
const methods = {
getCountry: () => {
console.log("I am");
}
};
// Check if the method exists
if (methods[method_name]) {
methods[method_name]();
} else {
console.error(`Method ${method_name} does not exist`);
}
In this example, I've created an object called methods that contains a method named getCountry. The method_name variable is then used as a key to access the method dynamically. The script checks if the method exists before calling it to avoid errors.
Make sure to replace the method content and add more methods to the methods object as needed for your application.
It looks like there is a syntax error in your code. You are missing a comma between the two methods inside the methods object. Here's the corrected version:
const method_name = {"key2":"getCountry2","key1":"getCountry1"};
const methods = {
getCountry1: () => {
console.log("I am getCountry1");
},
getCountry2: () => {
console.log("I am getCountry2");
}
};
methods[method_name.key1]();
// Check if the method exists
if (methods[method_name.key2]) {
methods[method_name.key2]();
} else {
console.error(`Method ${method_name.key2} does not exist`);
}
I added a comma after the definition of getCountry1 function inside the methods object. Also, in the error message, it should be method_name.key2 instead of just method_name.