0

I've seen EVERY example of how to replace anonymous functions with named ones. I'm looking for how a named function can be changed to an anonymous one. I'm looking to just optimize my code slightly. I understand how the anonymous function works, I just can't get the syntax right in this example. Additionally, the doWork function is a big beast. I need it to stay named.

NOTE: I did google, and I'm either searching the wrong terms, or not a lot of people want to know how to do this. I humbly beg for SO's forgiveness of my failure to find this answer somewhere else.

NOTE2: Please ignore my use of closure with this.formFields. Just assume it won't change ever. I'm setting it at an earlier time.

My code:

function doWork(serviceResponse, theFormFields){
     // Process stuff like jQuery or console test stuff etc
}

// THIS NAMED FUNCTION IS WHAT I WANT TO BE ANONYMOUS
function createCallback(formfields) {
   return function(data) {
        // This reference to the 'formfields' parameter creates a closure on it.
        doWork(data, formfields);

    };
}

// THE ABOVE FUNCTION *COULD* be anonymously declared in the getJSON 
$.getJSON(jsonService + callString, createCallback(this.formFields));
1
  • Just write it inline like mentioned. Where you can mention a function name you can mention a function definition, it will work the same. Not sure if there are advantages thought, I guess that depends. Commented May 12, 2016 at 12:51

1 Answer 1

2
$.getJSON(
    jsonService + callString,           // your param #1
    (function (formField) {             // here we create and execute anon function
                                        // to put this.formFields into the scope as formField variable
                                        // and then return required callback
        return function (data) {
            doWork(data, formField);
        }
    })(this.formFields)
);
Sign up to request clarification or add additional context in comments.

4 Comments

Although your answer is very similar to ihimv's answer, why do you include an additional parenthesis after you declare the anonymous, and he doesn't. Is this just more strict?
This way I've made two things with single line of code: 1. defined a function function (formField) { ... } 2. immediately called with argument value this.formFields. And I called it with an argument which was copied into the scope of that function and since that I'm not afraid if something will change the value of this.formFields.
okay this answer and my answer both are wrong. So i have deleted my answer
Can you elaborate? The code seems to work. What is wrong? Also, I chose this answer because stas.yaranov went to the trouble to explain why everything is as it is. I am trying to learn more.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.