TotomInc TotomInc - 3 months ago 7
Javascript Question

Update a string who was init with values returned from a function

Is there a way to update a string who was initialized with a value returned from a function?

Here is a example of what I'm speaking:

var level = 1,
returnLevel = function() {
return level;
},
str = 'level: ' + returnLevel();

level = 2;

// how to update the var str without doing 'level:' + level?


EDIT: real code, since it was asked (I minified this code a lot):

function returnPrice(what) {
return g.items[what].baseCost;
};

g.items = {
'item-1': {
baseCost: 100
},
'item-2': {
baseCost: 1000
},
'item-3': {
baseCost: 5000
}
};

g.console.commands = [
{
name: 'buy',
desc: 'command desc',
commands: [
{
name: 'buy item',
desc: 'buy specified item',
customDesc: [
'test desc $' + returnPrice('item-1') + '.',
'test desc $' + returnPrice('item-2') + '.',
'test desc $' + returnPrice('item-3') + '.'
]
}
]
}
];

Answer

Another way is to use str as a function and implement a toString method for calling the actual value without parenthesis.

var level = 1,
    returnLevel = function () {
        return level;
    },
    str = function () {
        function f() { }
        f.toString = function () {
            return 'level: ' + returnLevel();
        }
        return f;
    }();

console.log(str);
level = 2;
console.log(str);