javascript - 在 JavaScript 中用匿名函数替换命名函数

标签 javascript anonymous-function

我已经看过如何用命名函数替换匿名函数的每个示例。我正在寻找如何将命名函数更改为匿名函数。我希望稍微优化我的代码。我了解匿名函数的工作原理,但我只是无法在这个示例中获得正确的语法。 此外,doWork 函数是一个庞然大物。我需要它保留名称。

注意:我用谷歌搜索过,我要么搜索了错误的术语,要么没有很多人想知道如何做到这一点。我谦卑地请求SO原谅我未能在其他地方找到这个答案。

注意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));

最佳答案

$.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)
);

关于javascript - 在 JavaScript 中用匿名函数替换命名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187265/

相关文章:

php - 如何动态检查 PHP 中匿名函数预期的参数数量?

Haskell:带有两个参数的匿名函数

javascript - Content-Security-Policy 和外部 Javascript 文件

javascript - JQuery 和 Javascript 淡入淡出不起作用

javascript - 如何从数组中分割指定数量的元素?

c# - 将嵌套的匿名函数转换为 foreach 循环

javascript - jQuery Autocomplete 出现在 HTML 的顶部,附加到 body 标签的底部

javascript - Node.js 中的 Promise 链

Javascript 函数作用域 [Javascript 精要]

PHP 的 register_shutdown_function() 使用匿名函数