Introduction
JavaScript is a versatile and highly effective language, offering quite a lot of methods to do absolutely anything, like invoking features. One of many extra attention-grabbing and lesser-known strategies is invoking a perform whenever you solely have its identify as a string.
This Byte will take you thru the method of invoking JavaScript features from string names, and why you may wish to achieve this.
JavaScript Operate Invocation
Earlier than we get into the main points of invoking features from string names, let’s check out the best way to invoke fundamental JavaScript features. In JS, features are invoked by appending parentheses ()
to the perform identify. This may be performed instantly, as in myFunction()
, or not directly, as in myObject.myMethod()
.
perform sayHello() {
console.log("Hey, world!");
}
sayHello(); // Outputs: Hey, world!
Why Invoke Features from String Names?
If you happen to do not have already got a well-thought-out state of affairs for doing this, you marvel why we might wish to do it in any respect. Effectively, there are just a few eventualities the place this may be helpful.
For example, you could be working with an API that returns a string indicating which perform ought to be executed, like a distant process name (RPC). Or, you possibly you are growing a plugin system the place plugins register their features by identify, and it’s good to name these features dynamically.
In these circumstances, with the ability to invoke a perform from its string identify is usually a highly effective device in your app.
Fundamental Technique: Utilizing the Window Object
Probably the most fundamental solution to invoke a perform from a string identify in JavaScript is to make use of the window
object. In a browser surroundings, all international JavaScript features change into strategies of the window
object. So, you’ll be able to entry these features as properties of window
utilizing bracket notation.
Here is a easy instance:
perform greet() {
console.log("Hey, world!");
}
var functionName = "greet";
window[functionName](); // Outputs: Hey, world!
On this code, we’re defining a perform greet
, then storing its identify as a string within the variable functionName
. We then use bracket notation to entry this perform as a property of window
and invoke it.
Be aware: This technique solely works for international features in a browser surroundings. It will not work for native features or in non-browser environments like Node.js.
Superior Technique: Utilizing JavaScript’s eval() Operate
A extra superior (and controversial) technique for invoking a perform from a string identify is to make use of JavaScript’s eval()
perform. The eval()
perform takes a string of JavaScript code and executes it. This implies you’ll be able to assemble a string representing the perform name you wish to make, and eval()
will execute it.
Here is the way you may do that:
perform greet() {
console.log("Hey, world!");
}
var functionName = "greet";
eval(functionName + "()"); // Outputs: Hey, world!
On this instance, we’re concatenating the string "()"
to the perform identify and passing the ensuing string to eval()
. This causes eval()
to execute the perform name as if it had been a line of JavaScript code.
Be aware: Use eval()
with warning! As a result of it executes arbitrary JavaScript code, it will possibly pose severe safety dangers if misused. At all times validate and sanitize any enter that you just move to eval()
.
Different Technique: Utilizing the Operate Constructor
One other solution to execute a perform from a string identify in JavaScript is by utilizing the Operate constructor. This technique is a little more superior, however it presents a whole lot of flexibility.
Here is the way it works:
let functionName = "sayHello";
let functionArguments = ["John"];
let functionBody = 'console.log("Hey, " + identify + "!");';
let func = new Operate('identify', functionBody);
func.apply(null, functionArguments);
Within the above instance, we create a brand new perform with the Operate
constructor. The constructor takes a variable variety of arguments. The final argument is the perform physique as a string, and the previous arguments are the names of the arguments for the perform.
After creating the perform, we are able to name it utilizing the apply()
technique, passing the arguments as an array.
Wait! Utilizing new Operate
like this to name code from a string is harmful. It opens up your software to all types of potential safety points. It is best to solely use this technique as a really final resort.
Executing Namespace Features
Generally, features usually are not international however are nested inside objects or “namespaces”. In such circumstances, we are able to nonetheless execute them by accessing the item properties.
Think about the next instance:
let myNamespace = {
myFunction: perform(identify) {
console.log('Hey, ' + identify + '!');
}
};
let functionName = "myFunction";
let functionArguments = ["John"];
myNamespace[functionName].apply(myNamespace, functionArguments);
On this instance, myFunction
is a property of the myNamespace
object. We will entry it utilizing bracket notation after which name it with the apply()
technique.
However what if the perform identify was laid out in dot notation? To make this work, you’d want to separate the item/perform names by the intervals and entry every object earlier than calling the perform. This may be achieved with a perform like this:
let myNamespace = {
features: {
hi there: perform(identify) {
console.log('Hey, ' + identify + '!');
}
}
};
let functionName = "features.hi there";
let context = myNamespace;
let namespaces = functionName.cut up(".");
let func = namespaces.pop();
for (let i = 0; i < namespaces.size; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
Utilizing this, we are able to execute features of arbitrary namespace depth.
Safety Concerns
Whereas these strategies might be fairly helpful, it is vital to keep in mind that executing code from a string is usually a safety danger. That is very true when utilizing the eval()
perform or the Operate
constructor, as they’ll execute any JavaScript code. If you happen to’re coping with consumer enter, this will result in code injection assaults.
Be aware: At all times validate and sanitize consumer enter earlier than utilizing it in your code. Keep away from executing code from strings every time doable.
Conclusion
On this Byte, we have confirmed just a few completely different strategies of executing a JavaScript perform when you have got its identify as a string. We have seen the best way to use the window
object, the Operate
constructor, and even the best way to execute features inside namespaces. Whereas these strategies might be helpful, it is vital to make use of them responsibly to keep away from potential safety dangers.