function Picker() {
this.status = [0, 0, 0];
this.progress = Picker.status[0];
}
var picker = new Picker();
picker.progress = 2;
现在,如果我检查进度和状态[0]所持有的信息,它们将会有所不同。
如何将这些作为引用而不是副本?
非常感谢
最佳答案
没有简单的方法,因为 JavaScript 不会将原始值存储为引用,但您可以这样做:
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
最典型的解决方案可能是使用 getter 和 setter,或者更改设计。
关于javascript - 分配变量值: Reference it instead of copying it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24779419/