javascript - js 更改变量会影响原始变量

标签 javascript variables

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

当我实例化一个新函数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/

相关文章:

javascript - 从给定的日期字符串中获取年份

javascript - 使用 javascript 中的 window.location 更改浏览器窗口

javascript - 当按钮位于表单标签之外时,jQuery 表单不会验证

java ;从另一个类访问成员实例变量

php - 将字符串和变量传递给 php 函数

php - 在 html 标签中的鼠标悬停中的 setTimeOut 函数中使用 php 变量

c++ - 如何扩展先决条件列表中的 makefile 变量?

javascript - 验证某些用户的 Passport 策略

javascript - 在点击事件中分配点击事件

r - 语言R : Variable doesn't change inside a 'for()' cycle?