Skip to content
Advertisement

How to link a javascript object property to another property of the same object?

Is there a way to link the value of one object property to the value of another?

The idea is, that I have something like an excepted interface so I need the propertys.name and .value for my obj. In this special case name is easily constructed from value (value is an array and name is array.toString())

I could use obj.value.toString() instead of value but the code needs to use obj.name to make it work for all cases.

I tried this code, but it does not produce the result I want. How could I achieve the desired behavior?

obj = {value: array, name: this.value.toString()}

Advertisement

Answer

You can use a getter.

var obj = {
  value: array,
  get name() {
    return this.value.toString();
  }
};
console.log(obj.value.toString() === obj.name); // true

You can even extend this to use a setter if need be.

var obj = {
  value: array,
  get name() {
    return this.value.toString();
  },
  set name(val) {
    this.value = val.split(','); // or any other operation you may need
  }
};
obj.name = '1,2,3';
console.log(obj.value); // ['1', '2', '3']
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement