I have this code
function changeFunc() {
return function(target: any, title: string, descriptor: PropertyDescriptor) {
descriptor.value = function () {
console.log(this.name);
};
return descriptor;
}
}
class Man {
name: string = "asdsds";
constructor(name: string) {
this.name = name;
}
@changeFunc()
getName() {
console.log("Hello");
}
}
var man = new Man('Manos Serifios');
man.getName();
In other words i try (with the decorator) to change the method
getName() {
console.log("Hello");
}
with this
function () {
console.log(this.name);
}
but this.name evaluated as undefined.
If i console log the "this" it seems that is the right(instance man).
A Method Decorator is declared just before a method declaration. The decorator is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.
In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.
In AngularJS, decorators are functions that allow a service, directive, or filter to be modified before it is used. There are four main types of angular decorators: Class decorators, such as @Component and @NgModule. Property decorators for properties inside classes, such as @Input and @Output.
Since decorators are an experimental feature, they are disabled by default. You must enable them by either enabling it in the tsconfig. json or passing it to the TypeScript compiler ( tsc ).
You don't have the context of a specific object instance inside the decorator method. The parameters are the following (from https://www.typescriptlang.org/docs/handbook/decorators.html):
Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
The name of the member.
The Property Descriptor for the member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With