Let’s first look at a function of JS
JavaScript eval() function
Definition and usage
The eval() function evaluates a string and executes the JavaScript code within it.
grammar
eval(string)
Parameter description
string required. A string to evaluate that contains a JavaScript expression to evaluate or a statement to execute.
return value
The value obtained by evaluating string (if any).
illustrate
This method only accepts raw strings as parameters. If the string parameter is not a raw string, the method will return unchanged. Therefore please do not pass String objects as parameters to the eval() function.
ECMAScript implementations allow an EvalError exception to be thrown if an attempt is made to override the eval property or assign the eval() method to another property and call it through that property.
Throw
If there are no legal expressions or statements in the parameters, a SyntaxError exception is thrown.
If eval() is called illegally, an EvalError exception is thrown.
If the Javascript code passed to eval() generates an exception, eval() will pass the exception to the caller.
Tips and Notes
Tip: Although eval() is very powerful, it is rarely used in actual use.
Example
Example 1
In this example, we'll apply eval() to several strings and see what results are returned:
Copy the code code as follows:
<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)")
document.write(eval("2+2"))
varx=10
document.write(eval(x+17))
</script>
Output:
200
4
27
Example 2
Look at what eval() returns in other cases:
Copy the code code as follows:
eval("2+3") // return 5
var myeval = eval; // EvalError exception may be thrown
myeval("2+3"); // EvalError exception may be thrown
You can use the following code to check whether the parameters of eval() are legal:
Copy the code code as follows:
try {
alert("Result:" + eval(prompt("Enter an expression:","")));
}
catch(exception) {
alert(exception);
}
The first method is to use eval in js
The following is an example written by myself
Copy the code code as follows:
call("showmsg");
function call(functionName){
eval("this."+functionName+"()");
}
function showmsg(){
alert("success");
}
eval can automatically recognize the string you spliced as a method and call it.
But the disadvantages are also great. Imagine that someone can call any of your methods by changing the name of the method where you call it.
The second method is mainly used as a self-defined method
Mainly because the second method requires a specific way to write
Copy the code code as follows:
function call(functionName) {
showmsgs["showmsg"]();
}
var showmsgs = { showmsg: function () {
alert("success");
}
}
call("showmsg");