Reputation: 402
Took me a lot of time to frame the title, alas it's still hard to comprehend.
Anyway this is what I wanna do, but don't know how to do it, or whether it is even possible, so please enlighten me.
Here it is:
const defaults = {
backgroundcolor: '#000',
color: '#fff',
getProps: [
'some value',
`${this.backgroundcolor}`,
`${this.color}`
]
};
I know I can call it outside of the Object like defaults.backgroundcolor
, but I wanna know if the above code is achievable too? Thanks in advance.
Upvotes: 0
Views: 35
Reputation: 350770
If you make getProps
a method, you can make it work:
const defaults = {
backgroundcolor: '#000',
color: '#fff',
getProps: function () { return [
'some value',
`${this.backgroundcolor}`,
`${this.color}`
];}
};
var x = defaults.getProps();
console.log(x);
If it has to be a a property that can be accessed without the function parentheses, then use defineProperty
:
const defaults = Object.defineProperty({
backgroundcolor: '#000',
color: '#fff',
}, 'getProps', {
get: function () { return [
'some value',
`${this.backgroundcolor}`,
`${this.color}`
];}
});
var x = defaults.getProps;
console.log(x);
You could also make a constructor which you execute immediately:
const defaults = new (function() {
this.backgroundcolor = '#000';
this.color = '#fff';
this.getProps = [
'some value',
`${this.backgroundcolor}`,
`${this.color}`
];
})();
var x = defaults.getProps;
console.log(x);
Upvotes: 1