简体   繁体   English

在JavaScript中修改函数参数是否是错误的做法

[英]Is it a bad practice to modify function arguments in JavaScript

I am writing a Node.js application. 我正在编写一个Node.js应用程序。 And there are some places where I have to modify function's arguments. 在某些地方,我必须修改函数的参数。 For instance, this Express middleware for adding user to request so I can view it later: 例如,此Express中间件用于添加用户以进行请求,以便稍后查看:

exports.fetchUserDetails = function (req, res, next) {
  httprequest(opts, function (err, res, body) {
    req.user = body.user;
    next()
  }
}

The thing is, I started to use static code analyzer (ESLint) and it is always complaining about reassigning function arguments ( http://eslint.org/docs/rules/no-param-reassign ). 问题是,我开始使用静态代码分析器(ESLint),并且它总是抱怨重新分配函数参数( http://eslint.org/docs/rules/no-param-reassign )。 I guess this rule is there for a reason. 我想这条规则是有原因的。

I know that modifying function parameters can be bad, like in this example: 我知道修改函数参数可能很糟糕,例如以下示例:

function modifyParam(param) {
  param.a = 2
}

var obj = { a: 1 };
console.log(obj); // outputs { a: 1 };
modifyParam(obj);
console.log(obj); // outputs { a: 2 };

But I don't really see the other way to refactor my middleware without arguments reassigning. 但是我真的没有看到无需重新分配参数即可重构中间件的另一种方法。

So my question is: 所以我的问题是:

  • When can I use params reassigning? 什么时候可以使用参数重新分配?
  • How can I refactor my middleware to avoid this? 如何重构中间件以避免这种情况? (or should I leave it like it is) (或者我应该保留原样)

I think in this case it's fine. 我认为在这种情况下就可以了。 You're setting up state that'll be used by subsequent functions that process the request. 您正在设置状态,该状态将由处理请求的后续功能使用。

The reason linters complain about this, is that it's often unclear when calling a function, that it will modify its arguments, leading to bugs, as you described in your question. linters对此抱怨的原因是,调用函数时通常不清楚,因为它将修改其参数,从而导致错误,如您在问题中所述。

But in this case, your function has only one caller, the express framework, and it's always clear under which circumstances your function will be called, so I don't think it's a problem here. 但是在这种情况下,您的函数只有一个调用方,即express框架,并且始终很清楚在哪种情况下会调用您的函数,因此在这里我认为这不是问题。

Example you provided does not include reassigning function arguments. 您提供的示例不包括重新分配函数参数。

exports.fetchUserDetails = function (req, res, next) {
  httprequest(opts, function (err, res, body) {
    req.user = body.user;
    next()
  }
}

You just attach new field to req reference, but you do not overriding req itself. 您只需将新字段附加到req引用,但不覆盖req本身。

Express middleware is using this approach from the beginning, and there is nothing wrong with that. Express中间件从一开始就使用这种方法,这没有错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM