【问题标题】:javascript first argument path last argument callbackjavascript第一个参数路径最后一个参数回调
【发布时间】:2011-11-04 22:58:10
【问题描述】:

我正在尝试围绕 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) {
}

让它们同时工作,就像在 express 中一样。

那么我如何编写一个包装函数,它知道第一个 arg 是路径,最后一个 arg 是回调,中间的其他所有内容都是可选的?

【问题讨论】:

    标签: javascript node.js arguments express


    【解决方案1】:

    有几个选项。一种是检查传递的参数的类型以找出传递的内容。如果您只想修改一个参数并且知道它是在特定位置传递的,则可以复制参数数组,修改该参数并使用 .apply() 传递修改后的参数(不管有多少)到原来的函数调用。

    对于第一个选项,您如何编写代码的细节取决于您允许的参数组合。这是一种方法,它允许中间有零个或一个选项,回调总是在最后。如果您愿意,可以使用多个选项使这更通用。在这种情况下,您可能会使用 arguments 数组。无论如何,这是一个版本:

    custom.get = function(path, option, callback) {
        // option is an optional parameter
        if (!callback || typeof callback != "function") {
            callback = option;   // callback must be the second parameter
            option = undefined;  // no option passed
        }
        if (option) {
            app.get(path, option, callback);
        } else {
            app.get(path, callback);
        }
    
    }
    

    对于第二个选项,这是一个通用版本,可让您修改路径参数并通过以下方式传递所有其余参数:

    custom.get = function() {
        // assumes there is at least one parameter passed
        var args = [].slice.call(arguments);    // make modifiable copy of arguments array
        var path = args[0];
    
        // do whatever you want with the path
    
        args[0].path = path;
        return(app.apply(this, args));
    }
    

    【讨论】:

    • 我想编辑包装器中的路径参数,所以不想完全传输所有参数
    • 一开始我误解了你的帖子,但现在改写了我的答案。
    • 我在我的答案中添加了另一个选项,只要路径选项作为第一个参数传递,它对于任意数量的选项都更通用。
    【解决方案2】:

    您可以使用函数提供的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"
    

    Demo.

    【讨论】:

    • 注意,我不相信你可以修改参数数组,所以这本身会识别参数,但不会让他修改一个并传递它们。
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2018-01-15
    • 2017-12-01
    • 1970-01-01
    相关资源
    最近更新 更多