Functional-style JavaScript: good practice to avoid argument mutation?

风流意气都作罢 提交于 2021-02-18 11:16:11

问题


This is a rather general question. Functional-style programming promotes the idea that a program is about transforming data through functions, and that mutation should be avoided (except possibly within a function, seen as a basic unit of abstraction).

But in this program:

function foo (bar) {
  bar.k1 = "bananas";
  return bar;
}

var o = { k1: "apples", k2: "oranges"};
var p = foo(o);

the external variable o is mutated within foo because bar is a reference to o, and, in the end, o === p (they reference the same object). But the functional paradigm would rather expect p to be fresh data.

The obvious solution is to clone the argument (e. g. using underscore/lodash's _.clone):

function foo (_bar) {
  var bar = _.clone(_bar);
  bar.k1 = "bananas";
  return bar;
}

But I wonder if this is the correct way to think about this problem. In a FP perspective, would you consider it a good practice to clone the objects passed as arguments if they will be mutated? (I am aware that not all objects can be cloned easily, if at all, but let's stick to simple cases). Your thoughts?


回答1:


Ideally the function should return a brand new object everytime it is called. Obviously for performance reasons it is not great, this is why persistent data structures exist. There are a few libraries for JS; immutable-js is arguably the most popular.

Otherwise mutating the object is fine, and in JS it is common practice, since not every project would immediately benefit from persistent data structures, plus the weight of the library.

Also note that in JavaScript everything is passed by value, but values themselves can hold references.



来源:https://stackoverflow.com/questions/28792326/functional-style-javascript-good-practice-to-avoid-argument-mutation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!