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

var picker = new Picker();

picker.progress = 2;

Now if I check the information held by progress and status[0] they will be different.

How can I make these a reference instead of copies?

Many thanks

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Dorjan
  • 2,027
  • 3
  • 16
  • 29

1 Answers1

1

There's no simple way, as JavaScript doesn't store primitive values as references, but you can do this :

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

The most typical solution would probably be to use getters and setters, though, or to change the design.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Interesting. I the project is being done with haste (at first) and I haven't coded in a few years thus started without a good structure. I can see this being a solution though! A lot more code than I thought it would be (I expected something like &= :D) – Dorjan Jul 16 '14 at 11:26