问题描述
这是一个相当普遍的问题.函数式编程提倡这样一种想法,即程序要通过函数来转换数据,并且应避免发生变异(可能在函数中除外,它被视为抽象的基本单元).
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).
但是在此程序中:
function foo (bar) {
bar.k1 = "bananas";
return bar;
}
var o = { k1: "apples", k2: "oranges"};
var p = foo(o);
外部变量o在foo中进行了突变,因为bar是对o的引用,最后是 o === p
(它们引用相同的对象).但是功能范式更希望p是新鲜数据.
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.
显而易见的解决方案是克隆参数(例如,使用下划线/破折号的 _.clone
):
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;
}
但是我想知道这是否是思考此问题的正确方法.从FP角度来看,如果将作为参数传递的对象突变,您是否认为克隆它们是一个好习惯?(我知道并不是所有对象都可以轻松克隆,但是让我们坚持简单的情况).你有什么想法吗?
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?
推荐答案
理想情况下,函数每次调用时都应返回一个全新的对象.显然出于性能原因,它并不是很好,这就是为什么存在持久数据结构的原因.有一些JS库. immutable-js 可以说是最受欢迎的.
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.
否则,对对象进行更改就可以了,在JS中,这是常见的做法,因为并非每个项目都会立即受益于持久性数据结构以及库的重量.
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.
还要注意,在JavaScript中,所有内容都是通过值传递的,但是值本身可以保存引用.
Also note that in JavaScript everything is passed by value, but values themselves can hold references.
这篇关于功能样式的JavaScript:避免参数突变的良好做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!