koleslaw
koleslaw

Reputation: 155

How do I set default key value pairs to object instances?

I'm defining individual styles for use, and would like to set defaults because right now, the code is redundant. Surely there must be a better way to approach this than to keep repeating "fontFace: 'Sen'". What is it?

var styles={};
styles.title={ x:0, y:0, fontFace: 'Sen', fontSize:28, color:'#7700dd', valign: 'top',};
styles.author={ x:1, y:1, fontFace: 'Sen', fontSize:12, color:'#363636' };
styles.comment={ x:2, y:3, fontFace: 'Sen', fontSize:8, color:'#363636' }

It'll get used like this:

slide.addText(myTitle, styles.title);
slide.addText(myAuthor, styles.author);
slide.addText(myComment, styles.comment);

Upvotes: 0

Views: 53

Answers (2)

gavgrif
gavgrif

Reputation: 15509

If all styles use the same fontface - insert it at the parent level

var styles={};

styles.fontFace = 'Sen';
styles.title={ x:0, y:0, fontSize:28, color:'#7700dd', valign: 'top',};
styles.author={ x:1, y:1, fontSize:12, color:'#363636' };
styles.comment={ x:2, y:3, fontSize:8, color:'#363636' }


slide.style.fontFace = styles.fontFace;

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44107

Yep - just have a default object, spread it first, then if any duplicate properties exist they'll be overridden.

const defaults = { fontFace: "Sen" /* All other properties */ };

styles.title = { ...defaults, /* All other properties - if duplicates, new values are set */ };

Upvotes: 2

Related Questions