1

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 :)

2
  • 2
    I think you're looking for decorators Commented Oct 4, 2023 at 21:17
  • I was trying to avoid that, but now I don't have to wonder if it's possible or not, so thank you very much :) Commented Oct 4, 2023 at 21:30

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.