TypeScript:传递对象的方法作为参数调用

时间:2020-12-20 01:57:32

标签: typescript

我最近开始在 cocos creator 中开发一款使用 TypeScript/JavaScript 作为语言的游戏,这是我的新手。我正在尝试创建一个复杂的回调方法,该方法将调用附加到对象数组的方法。

以下是我希望实现的功能的简短示例:

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

以及所有的接口和类实现

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";
    }
}

这段代码有很多问题,比如 instanceof 对接口不起作用,这不是一个大问题,我已经想出了几个解决方法(不是最优雅的,但不是一个大问题)。我遇到的真正麻烦是调用该方法,我环顾四周并找到了将函数/方法作为参数传递的代码,但它将参数作为独立函数而不是对象的实现方法运行。

如果你想看一个有效的例子,我在 Java 中使用反射得到了这个例子: Pastebin Link

2 个答案:

答案 0 :(得分:0)

很遗憾你做不到

interface BarI{
    bar():string;
}

if(element instanceof IBar) ...

因为接口不是“真正的”js 代码。你可以这样做

class BarI{
    bar(): string {
        ...
    }
}

var element = new IBar()

if(element instanceof IBar) ...

希望有帮助! This has some good info as well

答案 1 :(得分:0)

感谢@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

它还消除了检查接口的需要,这很好,因为在调用适当的方法时方法名称没有重叠。

相关问题