如何解决Javascript-通过函数名称和存储在变量中的参数来调用函数理想情况下不带“ eval”,但如果可行,则可以
相对于JS和node的新手(尽管我不认为它是node的事实很重要,但以防万一),但学习速度很快。这个问题的细节可能比需要询问的要多,但是在这种情况下,我尝试在其中包括一些我所做和尚未理解的解释。我怀疑这里缺少一些简单的东西...
我有一个A类,其中包含一堆(静态的,虽然我认为不重要?)函数。他们都做非常具体的事情。我还有另一个B类,它根据所需的函数名称和B中变量中的参数来调用A中的函数。
我知道我可以做这样的事情:
class A {
static doIt(theFunctionName,theArguments) {
if (theFunctionName == 'asdf') {
this.asdf(theArguments);
} else if (theFunctionName == 'qwer') {
this.qwer(theArguments);
} else if (theFunctionName == 'zxcv') {
this.zxcv(theArguments);
// } else if ( .. etc ...) {
// ... etc ...
} else {
//return some kind of error or whatever
}
}
static asdf(theArguments) {
//do stuff and return something
}
static qwer(theArguments) {
//do stuff and return something
}
static zxcv(theArguments) {
//do stuff and return something
}
}
class B {
constructor(...) {
this.theFunctionName = ...;
this.theArguments = [...];
}
myResult = A.doIt(this.theFunctionName,this.theArguments);
}
此外,我了解我可以动态访问对象的属性:
obj[myKey] = something;
或
myResult = obj[key]
但是功能吗?
我相信我正在寻找一种使用函数而不仅仅是属性的方法-一种不用所有if ... else if ...
的动态处理函数的方法?
我知道函数是JS中的第一类,并且可以像对象一样传递。但是我不确定这里是否有帮助,因为我自己没有传递函数,而是根据函数的名称和变量中的参数选择要调用的函数...对吗?
我尝试了几件事,试图使用带有功能的属性示例中的原理,但未获得期望的结果。我猜测这真的是做不成的(没有所有if... else if...
...或我缺少一些简单的东西。
任何帮助,我们将不胜感激。谢谢!
解决方法
函数是JavaScript中的一等成员。具有值为字符串的属性的对象与具有值为函数的属性的对象在基础上没有区别。普通括号表示法可以很好地与函数属性和方法配合使用:
class A {
static doIt(theFunctionName,theArguments) {
const fn = this[theFunctionName];
if (fn) {
return fn(theArguments);
} else {
//return some kind of error or whatever
}
}
static asdf(theArguments) {
//do stuff and return something
}
static qwer(theArguments) {
//do stuff and return something
return 'quer ran';
}
static zxcv(theArguments) {
//do stuff and return something
}
}
class B {
constructor() {
this.theFunctionName = 'qwer';
this.theArguments = 'foobar';
console.log(A.doIt(this.theFunctionName,this.theArguments));
}
}
const b = new B();
也就是说,这种设计模式看起来有些奇怪-A在实例上没有任何自有属性,因此A成为类有点奇怪。成为普通物体会更有意义。
const A = {
doIt(theFunctionName,theArguments) {
const fn = this[theFunctionName];
if (fn) {
return fn(theArguments);
} else {
//return some kind of error or whatever
}
},asdf(theArguments) {
//do stuff and return something
},qwer(theArguments) {
//do stuff and return something
return 'quer ran';
},zxcv(theArguments) {
//do stuff and return something
}
}
class B {
constructor() {
this.theFunctionName = 'qwer';
this.theArguments = 'foobar';
console.log(A.doIt(this.theFunctionName,this.theArguments));
}
}
const b = new B();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。