Typescript 方法使用方法装饰器返回未定义

Aru*_*mar 4 javascript typescript1.8

如果这是一个愚蠢的问题,我深表歉意。我是打字稿新手,正在学习打字稿装饰器。我找到了一个代码:MethodDecorator 来记录参数和结果。

日志装饰器

function log (target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) {
    let originalMethod = descriptor.value;
    descriptor.value = function (...args:any[]) {
        //before
        console.log(`${key} method called with args: ${JSON.stringify(args)}`);

        let result = originalMethod.apply(this, args);

        //after
        console.log(`${key} method return value: ${JSON.stringify(result)}`);
    }
    return descriptor;
}
Run Code Online (Sandbox Code Playgroud)

我在 Book 类中使用 @log 和 setId 和 getId 方法

书.ts

class Book{
    constructor(public id: number, public title: string, public publisher: string){}

    @log
    setId(id: number){
        this.id = id;
    }
    @log
    getId(): number{
        return this.id;
    }
}
Run Code Online (Sandbox Code Playgroud)

所有代码都工作正常,但当我运行此代码时 getId 返回未定义。

let book = new Book(1, "Learn TypeScript", "O\'Reilly Media");

let favBookId = book.getId();
console.log("Book before setId: ");
console.log(book);
console.log("Favourite book id: "+favBookId);

book.setId(5);
console.log("Book after setId: ");
console.log(book);
console.log("Favourite book id: "+favBookId);
Run Code Online (Sandbox Code Playgroud)

我的 tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "removeComments": false,
        "experimentalDecorators": true
    }
}
Run Code Online (Sandbox Code Playgroud)

编译并运行:

tsc -p ./
node book.js
Run Code Online (Sandbox Code Playgroud)

输出:

getId method called with args: []
getId method return value: 1
Book before setId:
Book {id: 1, title: 'Learn TypeScript', publisher: 'O\'Reilly Media' }
Favourite book id: undefined
setId method called with args: [5]
setId method return value: undefined
Book after setId:
Book {id: 5, title: 'Learn TypeScript', publisher: 'O\'Reilly Media' }
Favourite book id: undefined
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么 setId 可以按我想要的方式工作而 getId 却不能?

tsc -v: Version 1.8.10
Run Code Online (Sandbox Code Playgroud)

Rom*_*ert 6

我不知道为什么互联网上的所有帖子都引用了这样的例子,但我自己也遇到了关于方法装饰器上下文的问题originalMethod.apply(this, args);

这确实根本不起作用(我不知道这是一个ts错误还是什么)。

经过尝试错误后,我发现以下解决方案有效,允许您在基类中拥有正确的上下文:

function myDecorator(target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) {

        descriptor.value = function (...args:any[]) {
            // whatever code suits you here...
            // dont use "this", use "target"
            let result = originalMethod.apply(target, args);

        }
        return descriptor;
}
Run Code Online (Sandbox Code Playgroud)

现在这允许您执行以下操作:

export class Yeah {
    @myDecorator()
    helloWord() {
        let n = 5;
        return this.multiply(n);
    }

    multiply(a: number) {
       return a * 2;
    }

}
Run Code Online (Sandbox Code Playgroud)

干杯

  • 将目标作为参数传递将提供类原型而不是实际实例。使用“this”可能是大多数人想要的,但一定要使用实际的函数而不是箭头函数。 (5认同)