打字稿:从方法参数中调用方法

时间:2016-06-23 15:48:17

标签: javascript class methods typescript

我想这更像是一个好奇的问题,如果能够在打字稿中实际实现它会很好。

基本上我有一个类和两个方法就像这样:

这可能吗?


class MyClass{
   private cleanup(str:String):String{
     //clean up the string
     return str; //return sanitized string
   }
   //I want to do this
   insertString(this.cleanup(text_1:String), this.cleanup(text_2:String)){
     console.log(text_1 + text_2);
   }
}

而不是这个?


class MyClass{
   private cleanup(str:String):String{
     //clean up the string
     return str; //return sanitized string
   }
   //might get to long if I have to cleanup to many strings
   insertString(text_1:String, text_2:String){
     text_1 = this.cleanup(text_1)
     text_2 = this.cleanup(text_2)
     console.log(text_1 + text_2);
   }
}

1 个答案:

答案 0 :(得分:3)

您要实现的目标实际上并不是从其他方法签名中调用方法。它更多的是处理你的参数列表。

1:arguments黑客

您可以修改提供的arguments数组,相应的命名参数也会更改。

insertString(text_1:String, text_2:String) {
    // here text_1 and text_2 are not cleaned up yet
    for (var i = 0; i < arguments.length; i++) {
        arguments[i] = this.cleanup(arguments[i])
    }
    // text_1 and text_2 are now cleaned up
}

然而,这种做法很苛刻,你可以选择#2:

2:装饰者

我们声明了两个装饰器:一个名为cleanup参数装饰器:

function cleanup(target: Object, propertyKey: string | symbol, parameterIndex: number) {
    let cleanupParams: number[] = Reflect.getOwnMetadata("MyClass:cleanup", target, propertyKey) || [];
    cleanupParams.push(parameterIndex);
    Reflect.defineMetadata("MyClass:cleanup", cleanupParams, target, propertyKey);
}

一个名为CleanupMethod方法装饰器(它实际上是装饰工厂):

function CleanupMethod(func){
    return function (target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {
        let method = descriptor.value;
        descriptor.value = function () {
            let requiredParameters: number[] = Reflect.getOwnMetadata("MyClass:cleanup", target, propertyName);
            if (requiredParameters) {
                for (let parameterIndex of requiredParameters) {
                    arguments[parameterIndex] = func(arguments[parameterIndex]);
                }
            }
            return method.apply(this, arguments);
        }
    }
}

在装饰器中,我们保存一个列表,列出哪些参数应该在函数输入时清理,然后在每次调用时清理它们。

用法:

class MyClass{
    private cleanup(str:string):string{
        //clean up the string
        return '[sanitized ' + str + ']'; //return sanitized string
    }
    @CleanupMethod(MyClass.prototype.cleanup)
    insertString(text_1:string, @cleanup text_2:string){
        console.log(text_1 + text_2);
    }
    @CleanupMethod(MyClass.prototype.cleanup)
    insertNumber(n1: number, n2: number, @cleanup n3: number, n4: number, n5: number){
        console.log(`${n1} + ${n2} + ${n3} + ${n4} + ${n5}`)
    }
}
var m = new MyClass();
m.insertString('a', 'b') // outputs `a[sanitized b]`
m.insertNumber(10,20,30,40,50) // outputs `10 + 20 + [sanitized 30] + 40 + 50`

清理功能作为参数传递给CleanupMethod工厂。这样你就可以拥有不同的清理功能,例如:

@CleanupMethod(cleanupString)
insertString( @cleanup str1: string, @cleanup str2: string2 ){
    /*...*/
}
@CleanupMethod(cleanupNumber)
insertNumber( @cleanup n1: number ){
    /*...*/
}

如果需要,可以重写装饰器代码并将清理功能移动到参数装饰器,但这会增加所需的代码量:

@CleanupMethod
insertString( @cleanup(cleanupString) str1: string, @cleanup(cleanupNumber) n1: number ){
    /*...*/
}

More on decorators