[英]TypeScript: Passing object's method to call as an argument
I recently started working on a game in cocos creator which uses TypeScript/JavaScript as a language, which I'm new to.我最近开始在 cocos creator 中开发一个使用 TypeScript/JavaScript 作为语言的游戏,我是新手。 I'm trying to create a complex callback method that will call methods attached to an array of objects.
我正在尝试创建一个复杂的回调方法,该方法将调用附加到对象数组的方法。
Here is a short example of the functionality I'm hoping to achieve:这是我希望实现的功能的简短示例:
let arr:Base[] = [new Foo(), new Bar(), new FooBar()];
function func(interfaceType, method) {
arr.forEach(element => {
if(element instanceof interfaceType){
console.log(element.method());
}
});
}
func(BarI, bar()); //This should output bar foobar
func(FooI, foo()); //This should output 1 2
And all the interface and class implementations以及所有接口和 class 实现
interface FooI{
foo():number;
foo2():string;
}
interface BarI{
bar():string;
}
class Base { }
class Foo extends Base implements FooI{
foo(): number {
return 1;
}
foo2(): string {
return "A";
}
}
class Bar extends Base implements BarI{
bar(): string {
return "bar";
}
}
class FooBar extends Base implements FooI, BarI{
foo(): number {
return 2;
}
foo2(): string {
return "B";
}
bar(): string {
return "foobar";
}
}
This block of code has a lot of problems, like instanceof doesn't work for interfaces, that's not a huge problem, I have figured out a couple workarounds (not the most elegant, but not a huge problem).这段代码有很多问题,比如 instanceof 不适用于接口,这不是一个大问题,我想出了几个解决方法(不是最优雅的,但不是一个大问题)。 The real trouble I'm having is calling the method, I looked around and found code for passing functions/methods as a parameter, but it runs the parameter as an independent function rather than an object's implemented method.
我遇到的真正麻烦是调用该方法,我环顾四周,找到了将函数/方法作为参数传递的代码,但它将参数作为独立的 function 而不是对象的实现方法运行。
I got this example working using reflections in Java if you want to see a working example: Pastebin Link如果您想查看一个工作示例,我在 Java 中使用反射得到了这个示例: Pastebin Link
Unfortunately you can't do不幸的是你做不到
interface BarI{
bar():string;
}
if(element instanceof IBar) ...
since interfaces aren't "real" js code.因为接口不是“真正的”js 代码。 You could do
你可以做
class BarI{
bar(): string {
...
}
}
var element = new IBar()
if(element instanceof IBar) ...
I hope that helps!我希望这会有所帮助! This has some good info as well
这也有一些很好的信息
Thanks to @ Narkek Daduryan for the answer, I ended up doing感谢@Narkek Daduryan的回答,我最终做到了
let arr:Base[] = [new Foo(), new Bar(), new FooBar()];
function func(methodName) {
arr.forEach(element => {
if(element[methodName] !== undefined){
console.log(element[methodName]());
}
});
}
func("bar"); //This correctly output bar foobar
func("foo"); //This correctly output 1 2
It also cuts out the need to check for interfaces which is fine because there is no overlap for method names while calling the appropriate methods.它还消除了检查接口的需要,这很好,因为在调用适当的方法时方法名称没有重叠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.