javascriptfunctioninitializationinitializer

Is it possible to create a custom function initializer?


Sorry if this has already been answered, but I haven't been able to find the answer myself.

I was wondering if it is possible to create a custom function initializer? Something like this:

const newFunction = customFunction() { // Function code } 

Or

customFunction newFunction() { // Function code }

So that whenever the newFunction is called it is possible to run code around the function code. Something like this:

customFunction = {
    // Before code
    console.log("Starting customFunction")

    // Function code
    this()

    // After code
    console.log("Ending customFunction")
}

newFunction()

I hope it makes sense and thanks in advance :)


Solution

  • There is no way to create a custom initialiser. However, the same effect can easily be achieved using a higher order decorator function:

    function customFunction(otherFn) {
      return function() {
        // Before code
        console.log("Starting customFunction");
    
        // Function code
        const result = otherFn.apply(this, arguments);
    
        // After code
        console.log("Ending customFunction");
        
        return result;
      }
    }
    
    const newFunction = customFunction(function() { 
      console.log("running newFunction()");
    });
    
    newFunction();
    
    console.log("---------");
    
    const obj = {
      a: 40,
      giveMeTheAnswer: customFunction(function(b) {
        return `the answer is: ${this.a + b}`;
      })
    }
    
    console.log(obj.giveMeTheAnswer(2));
    .as-console-wrapper { max-height: 100% !important; }