is it possible to delcare an anonymous non-IIFE JavaScript function with a property

后端 未结 3 1686
鱼传尺愫
鱼传尺愫 2021-01-20 23:05

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

3条回答
  •  盖世英雄少女心
    2021-01-20 23:48

    To create a function, you have two options:

    • Function declaration

    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)

    • 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 = 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));

提交回复
热议问题