在javascript中指定值而不是引用

Mub*_*bas 25 javascript variable-assignment

我在javascript中分配对象时遇到了一些问题.

看看这个重现我的问题的示例代码.

var fruit = {
   name: "Apple"
};

var vegetable = fruit;
vegetable.name = "potatoe";
console.log(fruit);
Run Code Online (Sandbox Code Playgroud)

它记录

Object {name: "potatoe"}
Run Code Online (Sandbox Code Playgroud)

如何将值而不是对象的引用分配给另一个对象?

Luc*_*sta 35

您可以使用Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);
Run Code Online (Sandbox Code Playgroud)

  • @MubaharAbbas [参见此处](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) (2认同)