For example, in the world of AngularJS, you might see a construction like this:
myApp.factory('MyFactory', function(injectable) {
return function(param) {
this.saySomething = function() {
alert("Param=" + param + " injectable=" +injectable);
}
};
});
This code snippet can then be utilized in the following manner:
function(MyFactory) {
new MyFactory().saySomething();
}
Essentially, when the function provided to the factory
method is executed, the injectable
parameter is captured and will be accessible to new instances of MyFactory
without the need for re-specifying that parameter.
Now, if you are transitioning to TypeScript and aiming to define that your MyFactory
is instantiable and contains a saySomething
method, how can this be done elegantly?
One possible solution could involve the following code:
class MyFactory {
constructor(private injectable, private param) {}
saySomething() {
alert(...);
}
}
myApp.factory('myFactory', function(injectable) {
return function(param) {
return new MyFactory(injectable, param);
}
});
However, this revised approach slightly alters the API:
function(myFactory) {
myFactory().saySomething();
}
Is there a more refined and elegant way to achieve this objective? The addition of "new" distinctly signals the creation of a new unique object, which is the primary purpose of using a factory.