Javascript 为什么在使用typescript装饰器时为descriptor.value分配不同的函数
我不熟悉打字脚本,对decorator的使用感到困惑。我看到一些代码如下:Javascript 为什么在使用typescript装饰器时为descriptor.value分配不同的函数,javascript,typescript,decorator,typescript-decorator,Javascript,Typescript,Decorator,Typescript Decorator,我不熟悉打字脚本,对decorator的使用感到困惑。我看到一些代码如下: function log(target: any, key: string, descriptor: any) { const original = descriptor.value; descriptor.value = function (...args: any[]) { // Call the original method const result = origi
function log(target: any, key: string, descriptor: any) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
// Call the original method
const result = original.apply(this, args);
// Log the call, and the result
console.log(`${key} with args ${JSON.stringify(args)} returned ${JSON.stringify(result)}`);
// Return the result
return result;
}
return descriptor;
}
class Calculator {
// Using the decorator
@log
square(num: number) {
return num * num;
}
}
const calculator = new Calculator();
// square with args [2] returned 4
calculator.square(2);
...
descriptor.value = function (args: any) {
...
}
以下是我的问题:
Q1-我知道descriptor.value
包含原始的square
方法,然后另一个匿名函数被分配给descriptor.value
,然后返回descriptor
,我不确定它的确切含义,但我猜descriptor.value
包含的新函数将被调用,但是是谁干的?谁将调用decorator日志函数并获取返回的描述符
并调用其值函数?/谁将调用日志
函数
Q2-为什么新分配的匿名函数需要一个参数数组,一个参数就足够了,如下所示:
function log(target: any, key: string, descriptor: any) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
// Call the original method
const result = original.apply(this, args);
// Log the call, and the result
console.log(`${key} with args ${JSON.stringify(args)} returned ${JSON.stringify(result)}`);
// Return the result
return result;
}
return descriptor;
}
class Calculator {
// Using the decorator
@log
square(num: number) {
return num * num;
}
}
const calculator = new Calculator();
// square with args [2] returned 4
calculator.square(2);
...
descriptor.value = function (args: any) {
...
}
Q3-如果我没有将不同的函数分配给描述符.value作为:
function log(target: any, key: string, descriptor: any) {
const original = descriptor.value; //does nothing
return descriptor;
}
我假设square
方法将被调用两次,但它只被调用一次。那么,当您将descriptor.value
分配给一个新的不同函数时,为什么会调用新函数,这是不一致的呢