最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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()}

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()}
Share Improve this question edited Mar 31, 2016 at 2:26 Box Box Box Box 5,37010 gold badges52 silver badges71 bronze badges asked Mar 30, 2016 at 16:11 SergejSergej 3764 silver badges15 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 7

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']

If you need name to do something, you'd need a function:

obj = {value: ['foo','bar'], name: function() { return this.value.toString() }}


console.log(obj.value)
console.log(obj.name())

["foo","bar"]
foo,bar

No. You can't access a property upon initialization of the object. You can however set it after the creation of the obj.

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

Use a getter:

var obj = {
    value: [1, 2, 3, 4, 5, 6, 7, 8],
    get name(){
        return this.value.toString()
    }
}

console.log(obj.value)
console.log(obj.name)

发布评论

评论列表(0)

  1. 暂无评论