I have on one occasion found it useful to assign properties to functions before passing them as arguments to other functions.
That looked like this (sorry about any confu
functional composition is the right tract... here is a function for adding a prop to a different function.
var addProp = function(fun, propName, propVal){fun[propName] = propVal; return fun}
var funcOne = addProp(function(arg1,arg2){ return arg1 + arg2; }, "process",true);
var funcTwo = addProp(function(arg1,arg2){ return arg1 + arg2; }, "process",false);
the resulting code looks like that. and behaves as expected
Another way of doing this would be with a helper function:
const addProp = (fn, value) => { fn.process = value; return fn; };
const myFunc = addProp((arg1, arg2) => arg1 + arg2, true);
console.log(myFunc.process); // => true
console.log(myFunc(1, 2)); // => 3
You could probably also do this with a decorator, although that's a proposal for future versions of ECMASCript and would require transpilation to work.
To create a function, you have two options:
With this, no expressions are involved:
function funcOne(...) {
}
There is no way to tack on something like funcOne.process = true
except as a separate, standalone statement. (Not that that's a bad thing - I'd actually prefer such a second statement, it's probably the easiest to read)
With this, you have a function expression you can assign to a variable name - but you can't assign to the variable name and assign a property to the function at the same time with =
, because =
(the assignment operator) resolves to the value that was assigned, regardless of what sort of thing is on the left-hand side of the =
. This is why the following doesn't work:
var funcOne = function x(arg1, arg2) { return arg1 + arg2; }.process = true;
Above, the value that was assigned is true
, so the value that funcOne
receives is true
(no reference to the function remains).
But, you can use Object.assign
, which resolves to the first parameter, the object that was assigned to, to combine the declaration of the function and the additional property you want to assign to the function object in a single mostly-concise statement:
var funcOne = Object.assign(
(arg1, arg2) => { return arg1 + arg2; },
{ process: true }
);
console.log(funcOne(3, 4));