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

后端 未结 3 1676
鱼传尺愫
鱼传尺愫 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:45

    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.

提交回复
热议问题