为什么 ES6 在方法中复制 class 变量?

Why does ES6 copy class variables inside methods?

我有一个 JavaScript/ES6 class,其成员是一个名为 x 的数组,初始化为 [1,2,3,4]

当我在方法中声明一个新变量,称为 y,并为其分配 x,然后更改 x 中的值时,y 仍然存在不变,说明 yx.

的副本

如果我在同一方法中声明 y 并将其分配给名为 z 的变量,则修改 z 会更改 y,但不会更改 [=13] =].

这表示声明一个 class 级别数组(对象?)然后将其分配给方法内的变量会复制该对象。这与 C# 等语言有很大不同。

为什么在JavaScript/ES6中是这样实现的?

class Alpha {
  constructor() {
    this.x = [1, 2, 3, 4];
  }

  DoSomething() {

    console.log('x is ' + this.x); // x is 1,2,3,4

    let y = this.x;
    this.x = [99, 99, 99, 99];

    console.log('x is ' + this.x); // x is 99,99,99,99
    console.log('y is ' + y); // y is 1,2,3,4 (?)

    let z = y;
    z[1] = 888;

    console.log('x is ' + this.x); // x is 99,99,99,99
    console.log('y is ' + y); // y is 1,888,3,4
    console.log('z is ' + z); // z is 1,888,3,4

  }
}

let thing = new Alpha();
thing.DoSomething()

let y = this.x;
this.x = [99, 99, 99, 99];

y 现在指向 [1,2,3,4]....this.x 现在指向 新数组 [99,99,99, 99];

编辑

郑重声明,这与 ES6 无关

编辑#2

y 现在指向内存中包含数组 [1,2,3,4] 的位置,this.x 现在指向内存中包含数组 [99,99,99] 的不同位置,99];

这个问题的核心是对内存分配的理解。

这就是内存如何存储值以及变量如何指向内存中的不同值。

 Statement                 Value of x              Value of y
+------------------------+---------------------+-------------------+
|  let x = [1, 2, 3, 4]; |  [1, 2, 3, 4]       |                   |
|  let y = x;            |  [1, 2, 3, 4]       |   [1, 2, 3, 4]    |
|  x = [99, 99, 99, 99]; |  [99, 99, 99, 99]   |   [1, 2, 3, 4]    |
+------------------------+---------------------+-------------------+

基本上,两个变量 contain/point 具有不同的值,因此对一个变量的修改不会影响另一个。

与class或class方法无关,在javascript中一直存在。 let tab_origin = [ "aa", "bb", "cc" ]; let same_tab = tab_origin;

这使得tab_originsame_tab指向数组的相同地址。 换句话说,你只有一个数组和两个不同的变量来访问它。 same_tab[0] = "zz"; console.log( tab_origin[0] ); // => "zz"

请注意函数的这一点: 函数 myfunction(inTab) { inTab[1] = "ff" }<br> 我的函数(tab_origin); console.log(tab_origin[1]); // => "ff" !!

所以,如果你想要你的数组的副本,你必须这样做: let other_tab = Object.assign( [], tab_origin ); 顾名思义,此方法允许分配一个新对象 other_tab[2] = "xy"; console.log( tab_origin[2] ); // => "cc" - unchanged :) console.log( other_tab[2] ); // => "xy"

let tab_origin = [ "aa", "bb",  "cc" ];

let same_tab = tab_origin; 

same_tab[0] = "zz";
console.log( 'tab_origin[0]', tab_origin[0] ); // => "zz"

function myfunction(inTab)
{ 
  inTab[1] = "ff";
}  

myfunction(tab_origin);
console.log( 'tab_origin[1]', tab_origin[1] ); // => "ff"

let other_tab = Object.assign( [], tab_origin ); 


other_tab[2] = "xy";
console.log( 'tab_origin[2]', tab_origin[2] ); // => "cc"
console.log( 'other_tab[0]',  other_tab[2] );  // => "xy"