在javascript

时间:2016-05-12 12:43:25

标签: javascript anonymous-function

我已经看到了如何使用命名函数替换匿名函数的每个示例。我正在寻找如何将命名函数更改为匿名函数。我希望稍微优化我的代码。我理解匿名函数是如何工作的,我只是无法在这个例子中得到正确的语法。 此外,doWork功能是一个大野兽。我需要它来保持名字。

注意:我确实谷歌,我要么搜索错误的条款,要么不是很多人想知道如何做到这一点。我谦卑地请求原谅我未能在其他地方找到答案。

注意2:请忽略我对this.formFields的闭包使用。只是假设它永远不会改变。我是在较早的时候设置的。

我的代码:

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 个答案:

答案 0 :(得分: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)
);