Casper LI Wai Kin Casper LI Wai Kin - 13 days ago 5
Javascript Question

Ways to do String Addition inside Object Literal

Can I do some string additions inside an object literal?

Chrome gives me the following error message if I do

height: 'calc(100% - ' + String(this.padding) + 'px * 2)'
.


[ProjectContainer.js:15] Uncaught TypeError: Cannot read property
'padding' of undefined


var styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
textAlign: 'left',
padding: 10,
height: 'calc(100% - ' + String(this.padding) + 'px * 2)',
width: 'calc(100% - 10px * 2)',
overflowY: 'scroll'
}
}


However, if I make it as a function, no error message is displayed but the css seems not working. This may because the inline-style system does not call it as a function but variable.

var styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
textAlign: 'left',
padding: 10,
height: function() {return 'calc(100% - ' + String(this.padding) + 'px * 2)'},
width: 'calc(100% - 10px * 2)',
overflowY: 'scroll'
}
}


What is the best way to make the height to be
'calc(100% - 10px * 2)'
?

Answer

As noted in the comments, you can't use this to refer to your object literal as you are defining it. Instead it will refer to the global this, or the this in the current scope of the code. Basically you cannot use the properties of an object literal while you are still defining it, you will need to do so afterwards:

var styles = {
    root: {
        display: 'flex',
        flexWrap: 'wrap',
        textAlign: 'left',
        padding: 10,
        height: '',                     // Optional
        width: 'calc(100% - 10px * 2)',
        overflowY: 'scroll'
    }
}

styles.root.height = 'calc(100% - ' + String(styles.root.padding) + 'px * 2)';

console.log(styles);

Comments