Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading