很抱歉,这里的Javascript还是比较新的,所以希望这个问题不是太容易让人尴尬,但是:
我发现我在node.js(express)中编写了大量代码,大致如下:
app.get("urlscheme1", function (res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_taskABC();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
});
app.put("urlscheme1", function (res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_taskDEF();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
});
app.post("urlscheme1", function (res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_taskGHI();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
});
这似乎是非常浪费的。但是,我对JS中的所有prototype
和“子类化”语法/语义都不是很满意,但还不足以理解如何使其更好。有没有办法扩展现有的类(在这个例子中表达应用程序)让我做类似的事情:
app.get("urlscheme1", function(res, resp) {
do_something_ABC();
});
app.get("urlscheme1", function(res, resp) {
do_something_DEF();
});
app.get("urlscheme1", function(res, resp) {
do_something_GHI();
});
所有这些处理函数仍在执行那个“常用”代码吗?
谢谢!
答案 0 :(得分:3)
这样的事情会起作用:
function install(urlscheme, method, specific_task) {
function handler(res, resp) {
try {
auth_request(req); // throws on failure
validate_url_params(req); // throws on failure
common_tasks();
specific_task();
} catch (e) {
if (e.error == "auth") {
resp.send(....);
} else if (e.error == "url_scheme") {
resp.send(....);
} else {
resp.send(translate_error(e), code_for_error(e)):
}
}
}
app[method](urlscheme,handler); // app.post(), app.get(), etc.
};
install("urlscheme1","get", do_something_ABC );
install("urlscheme1","post", do_something_DEF );
install("urlscheme1","put", do_something_GHI );