Home >Web Front-end >JS Tutorial >JS saves the method name according to the variable and executes the method example_javascript skills

JS saves the method name according to the variable and executes the method example_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:53:151290browse
Copy code The code is as follows:

function a(){
alert("fun a() ");
}
function b(){
alert("fun b()");
}
var methodName = "";
//method1
methodName = "a";
function method1(methodName){
//Initialize this.func property,
this.func = function(){};
try{
//Here Use the eval method to treat the method represented by the method name we passed in as an object and assign it to the func attribute of method1.
//If the corresponding object of methodName cannot be found, the eval method will throw an exception
this.func = eval(methodName);
}catch(e){
alert(methodName "( ) does not exist! ");
}
}
var c = new m(methodName);
c.func();

/**
* method2, relatively concise
*/
methodName = "b";
function method2(methodName){
this.func = new Function(methodName "();");
}
var c = new m(methodName );
try{
c.func();
}catch(e){
Ext.Msg.alert(methodName "() does not exist!");
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn