26

I read on many places that you can auto launch js functions on load by doing :

$(function() {
    // code...
});

Or

var myFunc = function() {
   // code...
}();

My question is, how do you call these functions later ? Because the simple declaration

function myFunc() {
    // code...
}

can be easily recalled but doesn't auto-launch. I have to manually call them all on load, and that's annoying, take up spaces in the code and it can be an error source if i forgot one.

If you don't understand my explanations, here's an example :

I have a "weight" and a "height" field in my form, and i need to calculate the BMI (Body Mass Index). When the page loads, the weight and height are filled by the database, then i launch the calculation when everything's ready. But later, if the user changes the weight or the height, the BMI have to recalculate immediately. What's the best way to do that ? Using jquery or pure JS, I don't mind.

Thanks.

1 Answer 1

49

A reusable immediate function

var reference = (function thename(){

    //function body

    return thename; //return the function itself to reference

}()); //auto-run


reference(); //call it again
reference(); //and again

Note that calling the function returns a reference to the function you just called.

var anotherReference = reference(); //anotherReference === reference
Sign up to request clarification or add additional context in comments.

2 Comments

Does it matter if "reference" and "thename" are the same ?
@Willy maybe (tried it and it works), but I'd like to make them different to avoid confusion.

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.