我正在尝试围绕expressjs的app.get编写一个包装函数
get(和其他方法)接受作为参数,路径,一些选项,然后是回调.但有时你可以把选项留出来并仍然有用.
我曾经做过:
app.get(path, auth.loadUser, function () {
// example
})
所以这不起作用:
custom.get = function (path, callback) {
// ?? missing a spot in the arguments array
app.get(path, auth.loadUser, function () {
// example
})
}
我需要能够做到这一点:
custom.get (path, callback) {
}
还有这个:
custom.get (path, auth.loadUser, callback) {
}
让它们同时工作,就像在快递中一样.
那么如何编写一个知道第一个arg是路径的包装函数,最后一个arg是回调,中间的其他所有内容都是可选的?
解决方法:
您可以使用函数提供的arguments数组.
var custom = {
get: null
};
custom.get = function(path, callback) {
alert(arguments[0] + " " + arguments[1].bar + " " + arguments[arguments.length - 1]);
}
custom.get("foo", { bar: "bar" }, "baz"); // alerts "foo bar baz"