繁体   English   中英

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

[英]TypeScript: Passing object's method to call as an argument

我最近开始在 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

以及所有接口和 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";
    }
}

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

如果您想查看一个工作示例,我在 Java 中使用反射得到了这个示例: Pastebin Link

不幸的是你做不到

interface BarI{
    bar():string;
}

if(element instanceof IBar) ...

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

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

var element = new IBar()

if(element instanceof IBar) ...

我希望这会有所帮助! 这也有一些很好的信息

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM