A few of my colleagues and I have been experimenting with returning bound functions from constructors.
This allows us to make these functions that 'build' other functions, without calling them buildDispatcher or prepareAddition. Let me give an example:
function addition(a, b) {
return a + b;
}
function buildOffsetter(a) {
return (b) => addition(a, b);
}
var offsetter = buildOffsetter(42);
console.log(offsetter(10));
If I were to use a constructor instead, I could do this instead:
function addition(a, b) {
return a + b;
}
function Offsetter(a) {
return (b) => addition(a, b);
}
var offsetter = new Offsetter(42);
console.log(offsetter(10));
Now, a more real-life example might look like this:
function dispatchDataToUrl(url, data) {
$.ajax({
type: "POST",
url: url,
data: data,
error: () => console.log(`An error happened when sending [${data}] to [${url}].`)
});
}
function buildDispatcher(url) {
return (data) => dispatchDataToUrl(url, data);
}
var dispatcher = buildDispatcher("http://stackoverflow.com");
dispatcher("stackoverflow rocks");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
which could be built like this:
function dispatchDataToUrl(url, data) {
$.ajax({
type: "POST",
url: url,
data: data,
error: () => console.log(`An error happened when sending [${data}] to [${url}].`)
});
}
function Dispatcher(url) {
return (data) => dispatchDataToUrl(url, data);
}
var dispatcher = new Dispatcher("http://stackoverflow.com");
dispatcher("stackoverflow rocks");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So, we really like not having these "build"-functions that return bound functions.
My question is, is there any downside to this? Is there some hidden pitfall that we haven't stumbled into yet?
new Something(), I'm expecting an object, not a function. The builder functions are much clearer to me.