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 } 


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

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


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()");



const obj = {
  a: 40,
  giveMeTheAnswer: customFunction(function(b) {
    return `the answer is: ${this.a + b}`;

.as-console-wrapper { max-height: 100% !important; }

Leave a Reply