0

I am having hard time understanding this code:

function Console(target) {
  console.log('Our decorated class', target);
}

@Console
class ExampleClass {
  constructor() {
    console.log('Yo!');
  }
}

I got output as Our decorated class [Function: ExampleClass] after compiling and running using node why is it that i didnt get Yo!.Can you explain to me this code, I saved it as

decorators.ts

compiled using tsc --target ES5 --experimentalDecorators decorators.ts and then ran node decorators.js

documentation is too tough to understand

I am totally confused in angular we dont need to instantiate a class and everything works fine but here we have to.can you please tell me why we dont need to instantiate a class in typescript

7
  • You didn't call the code that actually says Yo and also: further reading of what decorators are typescriptlang.org/docs/handbook/… Commented Jan 4, 2021 at 20:21
  • @Pandelis i didnt get you how to call that Commented Jan 4, 2021 at 20:22
  • You'll need a statement like new Console() somewhere to get Yo! Commented Jan 4, 2021 at 20:25
  • @Evert thanks i am hard time understanding about decorators,can you please explain to me the work flow of above code] Commented Jan 4, 2021 at 20:27
  • @Evert but example class is having a constructor right Commented Jan 4, 2021 at 20:27

1 Answer 1

1

console.log('Yo!') is in the constructor of ExampleClass. But you have not actually constructed any instances of ExampleClass. You have only decorated the class object itself.

There is nothing special about a class decorator that would run the constructor of the class it decorates unless you specifically run code that instantiates it.


If you add new ExampleClass() to the end of your code, you will get the "Yo!" that you expect.

Sign up to request clarification or add additional context in comments.

3 Comments

I am totally confused in angular we dont need to instantiate a class and everything works fine but here we have to.can you please tell me why we dont need to instantiate a class in angular
I'm no angular expert, but are you talking about dependency injection? That means that you declare that you want a type of object, and then Angular instantiates that for you, then passes it to your code. The angular provided decorators probably have logic that registers them with the dependency injection framework and then instantiates them as needed. But there is nothing about a class decorator that would do that unless you make that decorator do that. @Console class MyClass {} is really just syntax sugar for Console(class MyClass {})
@somanraj, about decorators, take a look to medium.com/front-end-weekly/… and netbasal.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.