Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
    
this does not have the value you want it to have inside a static declaration. Javascript doesn't work that way. You can assign defaults.getProps after you've declared the object and then you can refer to other properties in the object. – jfriend00 yesterday
up vote 0 down vote accepted

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);

share|improve this answer
    
Thanks a lot. Works like a charm. Would I be able to do the same with an anonymous function, using () => ? I tried, didn't get it. – TheEarlyMan yesterday
1  
No, => syntax does not set the this keyword. – trincot yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.