javascript - 装饰器 : "this" is undefined when accessed in descriptor. 值

标签 javascript typescript decorator

我正在尝试装饰器,我写了一个装饰器,它基本上返回一个执行一些 `console.log 的新函数。

这是我的装饰器的样子:

function test(target, name, descriptor) {
    const original = descriptor.value;
    console.log("bbau");
    if (typeof original === 'function') {
        descriptor.value = function (...args) {
            console.log(`Arguments: ${args}`);
            try {
                console.log("executing");
                const result = original.apply(this, args);
                console.log("done");
                console.log(`Result: ${result}`);
                return result;
            } catch (e) {
                console.log(`Error: ${e}`);
                throw e;
            }
        }
    }
    return descriptor;
}

这就是我使用它的方式:

class TestController extends BaseController<//..> {
    // ... 
    @test
    testIt(req: Request, res: Response) : Response {
       this.sendResponse();
    }

    sendResponse(options: ISendResponseOptions, res: Response) : Response {
       // return response
    }
}

`` 但是,执行时会出现错误:Error: TypeError: Cannot read property 'sendResponse' of undefined

有什么想法吗?谢谢!

最佳答案

当您想从声明函数的上下文中捕获 this 时(或者当 this 无关紧要时),您通常应该使用箭头函数。在这种情况下,您确实希望 this 成为函数被调用的对象,因此您应该使用常规函数:

const test = (target, name, descriptor) => {
    const original = descriptor.value;
    if (typeof original === 'function') {
          descriptor.value = function (...args) {
            console.log(`Arguments: ${args}`);
            try {
                console.log("executing");
                const result = original.apply(this, args);
                console.log("done");
                console.log(`Result: ${result}`);
                return result;
            } catch (e) {
                console.log(`Error: ${e}`);
                throw e;
            }
        }
    }
    return descriptor;
}

您可以在 playground 中进行测试

如果您将此函数用作另一个函数的参数,您还应该调用 bind 为该函数设置 this(否则调用者将确定 这个):

router.route("/").post(testController.testIt.bind(testController))

关于javascript - 装饰器 : "this" is undefined when accessed in descriptor. 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53856135/

相关文章:

javascript - Jquery 事件委托(delegate)问题

reactjs - 为什么我的 Jest 测试在使用 Typescript 的 React Native 中失败?

visual-studio-2012 - Typescript 无法在 Build VS 2012 上编译

javascript - 我可以在装饰器方法中获取变量的名称吗?

ruby-on-rails - 在方法中使用 form_for 的 Draper

javascript - 在 Obj C 中,如何添加 SVG 蓝图图像并渲染 UIWebView 中的数据?

javascript - 检测通用自定义属性的值而不直接向元素添加代码?

javascript - 在 javaScript 中关闭模态后不添加表中的新行

javascript - Angular 2 - 使用 HTML Canvas 时出现 "Cannot read property ' getContext' of null"错误

python - 方法的装饰器参数不能是基于类的静态成员的列表理解