Search code examples
javascriptstringdynamiccomposition

Dynamic composition of strings


Is it possible to somehow compose a string dynamically? I've read a bit about pass-by-value and pass-by-reference, and thus I'm creating all the strings as objects.

Example:

var foo = {str: 'foo'};
var bar = {str: foo.str + 'bar'};
var baz = {str: bar.str + 'baz'};
foo.str = 'fuu';
console.log(baz.str); //expected 'fuubarbaz', got 'foobarbaz

Thanks in advance!


Solution

  • Nah, when you define things statically like that, they're going to use the variable when it was called. You could do something like this with getters though:

    let foo = {str: 'foo'};
    let bar = {get str() { return foo.str + 'bar'; }};
    let baz = {get str() { return bar.str + 'baz'; }};
    foo.str = 'fuu';
    console.log(baz.str); // properly outputs `fuubarbaz`
    

    The reason why this works is the magic of getters; instead of defining the property statically, you're defining a function that gets called when trying to access the property. This way it can "react" to any downstream changes, because it's always dynamically generated.