首页 > 解决方案 > 如何在 const 函数中获取参数值?

问题描述

下面是我的代码。

我想知道的是,在将参数传递给变量“ok”时,如何在箭头函数“response”中传递返回参数的数据。

const response = (statusCode, formatter = null) => {
    const hasFormatter = typeof formatter === 'function';
    const format = hasFormatter ? formatter : _ => _;

    return (data = null) => {
        const response = {
            statusCode: statusCode
        };

        // Why is the data delivered??
        if (data) {
            response.body = format(data);
        }

        return response;
    }
};

const ok = response(200, JSON.stringify);

// Here, I put the parameter value({foo: 'bar'}) in the variable 'ok'.
console.log( ok({foo: 'bar'}) );
// {statusCode: 200, body: "{"foo":"bar"}"}

标签: javascriptnode.jsecmascript-6

解决方案


在评论中你澄清了:

名为响应的函数似乎只有两个参数值。因此,我认为返回参数中名为“data”的参数值不能在“reponse”函数内部的任何地方导入,但事实并非如此。

我看到了你困惑的根源。你不是response在你得到的时候data调用,你是在调用它返回的函数。

在这里,您正在调用response并传递它的两个参数的参数:

const ok = response(200, JSON.stringify);

response返回一个函数,您在变量ok. 该函数ok在调用时使用您传递的参数response以及它自己的参数data。(更多关于它如何在这个问题的答案和我贫血的小博客上的一篇过时的帖子response中使用's 参数。)

所以当你这样做时:

ok({foo: 'bar'})

您正在调用response返回的函数,并为函数的参数传入一个data参数。


推荐阅读