1
export const foobar = {
    foo: 'hello',
    bar: this.foo
};

It wont work its: "undefined"

how can I access it?

3 Answers3

1

As far a I know, you can't, at least not like you're trying to do it. You can't use this, because you're not inside a class, so it points to the global context (if any, or undefined) and the other only option would be to use foobar itself, like this:

const foobar = {
    foo: 'hello',
    bar: foobar.foo
}

But this won't work, either, because, until the statement is finished, foobar is not defined, so you get an error.

I am afraid the only way is:

const foobar = {
    foo: 'hello',
    bar: undefined
}
foobar.bar = foobar.foo;
Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
1

Inside your exported const foobar, this represent the context which owns the constant and which is global\window, So you get the value as undefined.

You have to create a new scope which is owned by your constant, which can be achieved by creating a function and assigning to bar property. Like below :

export const foobar = {
    foo: 'hello',
    bar: function(){
        return this.foo;
    }
};

now this will hold the foobar constant context and you will able to access prop foo, by calling foobar.bar()(should return 'hello')

anoop
  • 3,812
  • 2
  • 16
  • 28
1

As other answers already mention, this was used incorrectly. It refers to same this context as in the scope foobar variable was defined. It is undefined when the script runs in strict mode.

In order to refer foo property, bar can be defined as a pair of getter/setter functions:

export const foobar = {
    foo: 'hello',
    get bar() {
      return this.foo;
    },
    set bar(v) {
      this.foo = v;
    }
};

A setter can be omitted in case it's a constant that isn't supposed to be modified.

Notice that descriptors suffer from performance penalty in plain objects in V8 (Chrome, Node.js, etc), in performance-critical places it's beneficial to define a descriptor on object prototype, e.g. with class syntax.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565