我已经看过如何用命名函数替换匿名函数的每个示例。我正在寻找如何将命名函数更改为匿名函数。我希望稍微优化我的代码。我了解匿名函数的工作原理,但我只是无法在这个示例中获得正确的语法。 此外,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/