Я пытаюсь изучить дескрипторы в Angular. Я пробую этот фрагмент кода только для того, чтобы посмотреть, как дескрипторы могут манипулировать исходными методами. Но я вижу, что оператор «console.info()» функции @squareLog выполняется первым, а остальная часть кода выполняется по порядку. Я 100% нуб в Typescript и Angular. Выход правильный? Это то, что следовало ожидать от этого кода? Если нет, то я где-то накосячил?
import { Component } from '@angular/core';
function log(target, name, descriptor){
//store the original function in a variable
const original = descriptor.value;
//do some manipulation with descriptor.value
descriptor.value = function(){
console.info("This function is with LOG as the descriptor");
}
//return the descriptor
return descriptor;
}
function squareLog (target, name, descriptor){
console.info("This function is with SQUARELOG as descriptor");
const original = descriptor.value;
descriptor.value = function(...args){
console.info("Arguments ", args, "were passed in this function");
const result = original.apply(this, args);
console.info("The result of the function is ", result);
return result;
}
return descriptor;
}
function classLog(className){
console.info(className);
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
@classLog
export class AppComponent {
title: string = 'Demonstration of decriptors';
constructor(){
this.aSimpleMethod();
console.info("This statement was generated by constructor: ", this.returnSquare(5));
}
@log
aSimpleMethod(){
console.info("Learning about descriptors");
}
@squareLog
returnSquare(a){
return a*a;
}
}
пожалуйста, посмотрите на это, может быть, это поможет вам typescriptlang.org/docs/handbook/decorators.html
Эй, спасибо, ребята! Но я понял, что там пошло не так. Поскольку операторы внутри descriptot.value() не выполнялись. Я думал, что функции (здесь, т.е. log, SquareLog), которые используются в качестве дескриптора, выполняются только тогда, когда вызывается функция, которую они обертывают (как в этом случае, вызывается в конструкторе). Но похоже, что код по-прежнему выполняется последовательно, и выполняется только descriptor.value, когда вызывается функция (aSimpleMethod, returnSquare), для которой используются дескрипторы. Функция, определенная для использования в качестве дескриптора, по-прежнему выполняется там, где она определена.
пожалуйста, поддержите мой ответ, рад узнать, помог ли я вам.





function f() {
console.info("f(): evaluated");
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
console.info("f(): called");
}
}
function g() {
console.info("g(): evaluated");
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
console.info("g(): called");
}
}
class C {
@f()
@g()
method() {}
}
интересный вопрос, я даже не знал об этом