很抱歉我不知道如何解释,但情况就像这个例子。
当我实例化一个新函数c
后,并更改值this.i
将直接影响a。
我该如何解决这个问题?我不知道更改 this.i
会影响 a
。
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
关于javascript - js 更改变量会影响原始变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303672/