gpt4 book ai didi

typescript - 如何使用TypeScript方法装饰器并保留常规的 `this`范围

转载 作者:行者123 更新时间:2023-12-03 16:13:10 25 4
gpt4 key购买 nike

请注意:此问题是由于在运行我的修饰方法时使用了GraphQL解析器。这意味着this的范围为undefined。但是,该问题的基础知识对于装饰者遇到问题的任何人都是有用的。

这是我想使用的基本装饰器(我的装饰器中有更多代码):

const someDecorator = (argPassed: any) => {

return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {

const originalMethod = descriptor.value;

// DO stuff here...
console.log(argPassed);

// Wrapping the original method
descriptor.value = (...args: any[]) => {

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

return result;
};
};
};

我在装饰器中使用箭头函数,这是我可以使其返回某种范围的唯一方法,尽管它不同于普通的 this范围。

这是我正在使用的类以及我正在装饰的方法:

class SomeClass {

constructor() {
}

@someDecorator('Passing this in...')
public doingSomething(argPassed: string) {

console.log(this); // Returns: { default: SomeClass { otherMethodInMyClass: [Function] } }

// Meaning i can't do this
// this.otherMethodInMyClass is not a function
this.otherMethodInMyClass(argPassed);

}

private otherMethodInMyClass = (argPassed: any) => {
// Let's go for it...
}

}

当前,装饰器将 doingSomething的范围传回为:
{ default: SomeClass { otherMethodInMyClass: [Function] } }

当不使用装饰器时,我得到:
SomeClass { doingSomething: [Function], otherMethodInMyClass: [Function] }

这是正常行为吗?如果没有,我在做什么错?
如果是这样,我该如何允许我的方法在以后调用其他方法时使用其自己的范围。

更新:
正如@jcalz正确提到的,箭头函数没有获得自己的 this上下文。但是,当我在装饰器上使用非箭头函数时, this返回为 undefined

提前致谢

最佳答案

您问题中的问题似乎是您使用箭头函数作为方法,因此建议不要使用arrow functions don't get their own this context

您继续说,更改此设置不能解决您的问题,但是我无法重现此问题:

const someDecorator = (argPassed: any) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
console.log("ARGPASSED: ");
console.log(argPassed);
// anonymous function, not arrow
descriptor.value = function (...args: any[]) {
const result = originalMethod.apply(this, args);
return result;
};
};
};

class SomeClass {
constructor() { }

@someDecorator('Passing this in...')
public doingSomething(argPassed: string) {
console.log("THIS: ")
console.log(this);
this.otherMethodInMyClass(argPassed);
}

private otherMethodInMyClass = (argPassed: any) => { }
}

new SomeClass().doingSomething("abc");
// ARGPASSED:
// Passing this in...
// THIS:
// Object { otherMethodInMyClass: otherMethodInMyClass() }

Link to code in Playground

在我看来很好。如果问题仍然存在,则可能要在问题中包括有关配置的更多详细信息。确保您的问题中的代码构成 reproducible example总是有帮助的。祝你好运!

关于typescript - 如何使用TypeScript方法装饰器并保留常规的 `this`范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56189503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com