I know this sounds silly, but now my curiosity has me stuck on this idea. Is it possible to declare a collection of key/value pairs, like var collection = {a:"1", b:"2"}
and then have a third pair saying c: "3" + b.value?
First way, using a property getter
.
Please note c
is a property as b
and c
.
var collection = {
a: 1,
b: 2,
get c() {
return this.a + this.b;
}
};
console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c); // 3
Second way, using concise method in ES6 or a more "classical" function declaration in ES5.
Please note c
is now a function.
let collection = {
a: 1,
b: 2,
c() {
return this.a + this.b;
}
};
console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c()); // 3 called as a function
Third way, using a dedicated function for initialization.
This is useful if you have a more complex initialization, maybe on more properties, and could work similarly as a "constructor".
var collection = {
a: 1,
b: 2,
c: 3,
init: function() {
this.c = this.a + this.b;
}
};
collection.init();
console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c); // 3
Forth way, directly on c
property.
var collection = {
a: 1,
b: 2,
c: undefined
};
collection.c = collection.a + collection.b;
console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c); // 3
Regarding specifically your question, I would solve it using a getter
and appending value "3" in front of b
(please note result is of type string), example:
var collection = {
a: 1,
b: 2,
get c() {
return '3' + this.b;
}
};
console.log(collection.a); //1
console.log(collection.b); //2
console.log(collection.c); //"32"
console.log(typeof collection.c); // string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With