js更改变量会影响到原始变量

js Change variable will affect to original variable

本文关键字:变量 原始 影响 改变 js      更新时间:2023-09-26

很抱歉,我不知道如何解释,但情况就像这个例子。

我瞬间一个new function c后,改变值this.i会直接影响到a.

我该如何解决这个问题??我不知道this.ia的影响。

http://jsbin.com/iPIkomu/1/edit

var a = { c: 1 };
var b = function(){
  this.i = a;
  this.i.c = 2;
};

var c = function(){
   this.i = a;
   alert(this.i.c);
};
c.prototype.set = function(){
  this.i.c = 4;
  alert(a.c);
};
d =new c();
d.set();

使用此

let person1 = { name: 'Vitor', birthYear: 1995 };
// ES6 method
let person2 = Object.assign({}, person1);

如果是ArrayObject

let person1 = [{ name: 'Vitor', birthYear: 1995 },
              { name: 'Mark', birthYear: 1998 }];
// ES6 method
let person2 = Object.assign([], person1);

参考:https://hackernoon.com/javascript-reference-and-copy-variables-b0103074fdf0

对象总是通过引用传递。CCD_ 6和CCD_。

要获得不同的对象,您只需要执行this.i = {c:1};或类似操作。

我建议更改:

var a = { c: 1 };
to
var a = function() { return { c: 1 }; }

然后是

this.i = a;
to
this.i = a();

做这样的事情,你会确保你总是得到一个新的对象。使用您的代码,您引用的是同一个对象。

由于"a"是一个对象,因此通过将它们等同起来,它将引用传递给"a",从而对两个变量进行更改。你可以使用2种方法中的任何一种-

this.i=JSON.parse(JSON.stringfy(a));

this.i=Object.assign({},a);