Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 分配变量值:引用它而不是复制它_Javascript_Variables - Fatal编程技术网

Javascript 分配变量值:引用它而不是复制它

Javascript 分配变量值:引用它而不是复制它,javascript,variables,Javascript,Variables,现在,如果我检查progress和status[0]保存的信息,它们将不同 我怎样才能把这些作为参考而不是副本 非常感谢没有简单的方法,因为JavaScript不会将原始值存储为引用,但您可以这样做: function Picker() { this.status = [0, 0, 0]; this.progress = Picker.status[0]; } var picker = new Picker(); picker.progress = 2; 不过,最典型的解决

现在,如果我检查progress和status[0]保存的信息,它们将不同

我怎样才能把这些作为参考而不是副本


非常感谢

没有简单的方法,因为JavaScript不会将原始值存储为引用,但您可以这样做:

function Picker() {
    this.status = [0, 0, 0];
    this.progress = Picker.status[0];
}

var picker = new Picker();

picker.progress = 2;

不过,最典型的解决方案可能是使用getter和setter,或者更改设计。

可能重复@Curt。我不知道这是怎么重复这个问题的。不,我不知道这是重复的。你为什么要找推荐人?有什么原因吗@Cerbrus@我正在使用一个数组作为活动数据的杂项存储,并想为其中一个添加一个更简单的名称的引用。看看@dystroy的答案,显然这是有可能的。很有趣。我认为这个项目正在仓促地完成(一开始),我已经有几年没有编写代码了,因此没有一个好的结构就开始了。不过,我认为这是一个解决方案!比我想象的要多得多的代码(我期望像&=:D这样的代码能够完美地工作,先生)。非常感谢。
function Picker() {
    this.status = [0, 0, 0];
    Object.defineProperty(this, 'progress', {
      get : function(){ return this.status[0] },
      set : function(p){ this.status[0] = p },
      enumerable : true
    });
}

var picker = new Picker();
picker.progress = 2;
console.log(picker.status[0]) // logs 2