这是克隆任何对象/功能/等的有效/安全方法吗?在ES6中?

时间:2018-11-14 01:16:41

标签: javascript variables ecmascript-6 clone immutability

我想知道这是否是克隆变量的安全方法:

// the original variable definition:
let varIWantToCopy = 'hello world'

// the clone variable's definition:
let {varIWantToCopy: cloneOfVarIWantToCopy} = {varIWantToCopy}

// mutating the original value:
varIWantToCopy = 'goodbye world'

// should log out 'hello world':
console.log(cloneOfVarIWantToCopy)

感谢您抽出宝贵的时间对此进行研究。

亲切的问候,

哈里

1 个答案:

答案 0 :(得分:1)

如果您真的想克隆一个对象,我认为应该使用lodash。 There are several clone functions in lodash that you can use depending on your requirements.

// or you can use lodash/clone
import cloneDeep from 'lodash/cloneDeep';

var objects = [{ 'a': 1 }, { 'b': 2 }];

var cloned = cloneDeep(objects);

console.log(cloned[0] === objects[0]); // this will be false

因此,如果您更改cloned [0]的值,则对象[0]的值将保持不变。