I'm working on a backend solution in Node.js and Express, using Typescript. I'm trying to do dependency injection similar to Angular, but lacking the @Injectable() decorator I'm doing this:
Dependency:
export class SomeDependency {
public someMethod() {
console.log('Some method is running');
}
}
Parent:
import { SomeDependency } from './someDependency';
export class Whatever {
constructor(
private someDependency = new SomeDependency()
) {}
public doSomething() {
console.log('Look, I\'m doing something!');
this.someDependency.someMethod();
}
}
It works, but it may not be the best way. Any suggestions on how to improve it are appreciated.
On the other hand, what do you guys think: is it better to import dependencies like this, in the constructor, or create new instance every time, or most of the time? Like this:
import { SomeDependency } from './someDependency';
export class Whatever {
public doSomething() {
console.log('Look, I\'m doing something!');
new someDependency().someMethod();
}
}
As SomeDependency isn't a singleton, I wonder which one is less efficient: keeping an instance alive in the parent, or creating a new one every time, letting the garbage collector take care of it when the call finished.
classwhen you need to bundle data together with methods that operate on that data. If you have only methods, a plain function (or object of functions) would make more sense. If you have only data, a plain object or array would make more sense. For this example here, I'd doimport { someMethod } from './someMethod';wheresomeMethodis the function - then just call the function whenever needed.