0

I'm working on an ionic 2 project which uses angular 2.

I just have this in mind if there's a way I can create a variable to bind to another variable(s).

Let's say,

let x = 1;

let y = x;

where y will have the exact value of x even when it changes.

And if it does work, can I also do this?

let x = 1;

let y = 1;

let z = x + 1;

I'd like to know if this is possible or not. Just had this in mind. Thanks and cheers!

philnash
  • 70,667
  • 10
  • 60
  • 88
Vince Banzon
  • 1,324
  • 13
  • 17

2 Answers2

0

In Angular components and providers this is solved with property accessors:

class SomeService {
  x = 1;

  get y() {
    return this.x;
  }

  get z() {
    return this.x + 1;
  }
}

It's not possible to pass scalar value by reference (and there are usually no reasons to do that in Angular).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

Javascript does not allow passing reference of the primitive types. So you can achieve this by wrapping them in an object.

let x = { 
    value: 1,
    get z() { return this.value + 1}
}

let y = x;

y.value = 10;   // Now x.value is also 10
shawon191
  • 1,945
  • 13
  • 28