-3

I have a json object as follows;

export const initialState = {

    name: '',
    acceptable: false,
    identified: false,
    variation: false,
    variationText: () => {
      return name.toUpperCase() //as an example
    }
    
}


//use it kind of like this, so that the item's properties are transposed, but any missing attributes
//or the methods are maintained.
return {...initialState, ...item}

When I attempt to access the attributes within the method, it isn't available.

Thanks you.

Dean
  • 75
  • 1
  • 8
  • 1
    *"export cost initialState"* co**n**st? – T.J. Crowder Oct 29 '20 at 14:06
  • I guess it would be possible to use `new class { /*...(but with ...=...;)*/ }()`, to have the arrow function's `this` bind to the object, but it feels like it would be bad style. More of a "look what i can do", than properly solving the issue? – ASDFGerte Oct 29 '20 at 14:17
  • spelling mistake, apologies. I'll update to const – Dean Nov 05 '20 at 16:53

1 Answers1

2

JavaScript dosen't have any form of implicit this like some other languages do, to access a property on an object you have to explicitly refer to the object (unless you use the deprecated with statement).

In your example, you'd use the name of the constant:

export const initialState = {

    name: '',
    acceptable: false,
    identified: false,
    variation: false,
    variationText: () => {
      return initialState.name.toUpperCase()
//           ^^^^^^^^^^^^^
    }
    
}

Side note: variationText is not a method in your code, it's an arrow function bound to a property. This is important because if it were a method, in addition to using initialState as shown above, you could probably (depending on how the method were called) use this. But you can't with an arrow function assigned to a property, because arrow functions close over this, they don't get them set by how the function is called. (More here.)

So if you made it a method, and if the method were called in the usual way, you could use this:

export const initialState = {

    name: '',
    acceptable: false,
    identified: false,
    variation: false,
    variationText() {
//  ^^^^^^^^^^^^^^^^^
      return this.name.toUpperCase()
//           ^^^^^
    }
    
}

But it's possible to call that method with the wrong this; details here and here.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639