Skip to content Skip to sidebar Skip to footer

Is It Possible To Delcare An Anonymous Non-iife Javascript Function With A Property

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 confusion betwe

Solution 1:

To create a function, you have two options:

  • Function declaration

With this, no expressions are involved:

functionfuncOne(...) {
}

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)

  • Function expression

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 = functionx(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));

Solution 2:

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

Solution 3:

Another way of doing this would be with a helper function:

constaddProp = (fn, value) => { fn.process = value; return fn; };

const myFunc = addProp((arg1, arg2) => arg1 + arg2, true);

console.log(myFunc.process); // => trueconsole.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.

Post a Comment for "Is It Possible To Delcare An Anonymous Non-iife Javascript Function With A Property"