A sample introduction to JS dynamic call method names

  • 2020-03-30 00:57:17
  • OfStack

Let's look at a function of JS

The JavaScript eval () function
Definition and usage

The eval() function evaluates a string and executes the JavaScript code in it.
grammar

The eval (string)

Parameters to describe

The string must be. A string to evaluate that contains a JavaScript expression to evaluate or a statement to execute.

The return value

The value obtained by evaluating the string, if any.

instructions

This method accepts only the original string as an argument, and if the string argument is not the original string, the method returns unchanged. So don't pass a String object as an argument to the eval() function.

The ECMAScript implementation allows an EvalError exception to be thrown if you try to override the eval property or assign the eval() method to another property and invoke it through that property.

throw

If there are no valid expressions and statements in the arguments, 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() passes the exception to the caller.

Hints and comments

Tip: while eval() is very powerful, it's not used very often in practice.

The instance

Example 1

In this case, we'll use eval() on several strings and see what comes back:
 
<script type="text/javascript"> 

eval("x=10;y=20;document.write(x*y)") 

document.write(eval("2+2")) 

var x=10 
document.write(eval(x+17)) 

</script> 

Output:

200
4
27

Example 2

Look at what eval() returns in other cases:
 
eval("2+3") //Return to 5
var myeval = eval; //An EvalError exception may be thrown
myeval("2+3"); //An EvalError exception may be thrown

You can use the following code to check whether the argument to eval() is valid:
 
try { 
alert("Result:" + eval(prompt("Enter an expression:",""))); 
} 

catch(exception) { 
alert(exception); 
} 

The first is to use eval in js

Here is an example written by myself
 
call("showmsg"); 

function call(functionName){ 
eval("this."+functionName+"()"); 
} 
function showmsg(){ 
alert("success"); 
} 

Eval automatically recognizes strings you concatenate as methods and calls them.

But there's a big downside, too. Imagine someone changing the name of the method you're calling, and calling any method you want.

The second method is mainly used as a self-defined method

Mainly the second method requires a specific way to write it
 
function call(functionName) { 
showmsgs["showmsg"](); 
} 

var showmsgs = { showmsg: function () { 
alert("success"); 
} 
} 
call("showmsg"); 

Related articles: