'this' 在应用装饰器后在方法中变为未定义

'this' becomes undefined in method after apply decorator

上下文:我想为 运行 构建一个装饰器,一个拦截器来格式化 return 值。

问题:'this'在我应用装饰器后变得未定义。

// decorator
function UseAfter(this: any,  fn: (...args: any) => any){
    return (target: any, key: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value

        descriptor.value = (...innerArgs:any) => {
            let result = originalMethod.apply(this, innerArgs)

            return fn(result)
        }
    }
}

const middleware = (arg1: any) => {
    return {
        data: JSON.stringify(arg1)
    }
}

class Test {

    otherInstanceMethod() {
        console.log('accessing instance method')    
    }

    @UseAfter(middleware)
    method1() {
        console.log(this) // < --- undefined
        this.otherInstanceMethod()
        return 'ok'
    }
}

const test = new Test()
test.method1()

为了完整起见。

如果我们想保留 this 的上下文,我们不应该对描述符使用箭头函数。

// decorator
function UseAfter(this: any,  fn: (...args: any) => any){
    return (target: any, key: string, descriptor: PropertyDescriptor) => {
        const originalMethod = descriptor.value

        // this should not be a arrow function
        descriptor.value = function (...innerArgs:any) { 
            let result = originalMethod.apply(this, innerArgs)

            return fn(result)
        }
    }
}

const middleware = (arg1: any) => {
    return {
        data: JSON.stringify(arg1)
    }
}

class Test {
    otherInstanceMethod() {
        console.log('accessing instance method')    
    }

    @UseAfter(middleware)
    method1() {
        console.log(this)
        this.otherInstanceMethod()
        return 'ok'
    }
}

const test = new Test()
test.method1()


这将输出 -

Test {}
accessing instance method