gpt4 book ai didi

javascript - 用于验证方法使用的 Typescript 装饰器

转载 作者:行者123 更新时间:2023-11-30 11:44:15 25 4
gpt4 key购买 nike

我想创建一个可以应用于方法的装饰器,它的目标是控制是否允许您运行某种方法。这意味着它应该有一定的条件,如果通过,它将照常运行(也在相同的上下文中)

这是我对此进行的拍摄,但由于对象具有私有(private)成员而失败,现在当我运行该函数时无法访问:

return function(target:any, propertyKey: string, descriptor: PropertyDescriptor){
var funcToRun = descriptor.value;
descriptor.value = () => {
if(true) { //if has permissions
return p.call(target);
}
}
}

提前致谢。

最佳答案

我不会更改传递的描述符,而是返回更改后的副本。

这是您所要求的工作版本:

function deco(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const newDescriptor = Object.assign({}, descriptor);

newDescriptor.value = function () {
if (this.x > 0) {
return descriptor.value.apply(this, arguments);
} else {
throw new Error(`can't invoke ${ propertyKey }`);
}
}

return newDescriptor;
}

class A {
constructor(private x: number) {}

@deco
methodA() {
console.log("A.methodA");
}
}

let a1 = new A(10);
a1.methodA(); // prints: "A.methodA"

let a2 = new A(-10);
a1.methodA(); // throws error

( code in playground )

关于javascript - 用于验证方法使用的 Typescript 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41535265/

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