0

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.

1
  • 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. Commented Nov 18, 2016 at 6:20

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
No, => syntax does not set the this keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.