在 javascript 中用匿名函数替换命名函数
Replace named function with anonymous in javascript
我已经看过每个如何用命名函数替换匿名函数的例子。我正在寻找如何将命名函数更改为匿名函数。我希望稍微优化我的代码。我了解匿名函数的工作原理,只是无法正确理解此示例中的语法。
此外, doWork 功能是一个大野兽。我需要它来保持命名。
注意:我做了 google,但我不是在搜索错误的术语,就是没有很多人想知道如何执行此操作。我谦卑地请求 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)
);
我已经看过每个如何用命名函数替换匿名函数的例子。我正在寻找如何将命名函数更改为匿名函数。我希望稍微优化我的代码。我了解匿名函数的工作原理,只是无法正确理解此示例中的语法。 此外, doWork 功能是一个大野兽。我需要它来保持命名。
注意:我做了 google,但我不是在搜索错误的术语,就是没有很多人想知道如何执行此操作。我谦卑地请求 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)
);