When working with JavaScript, there is no implicit this
feature like in some other programming languages. To access a property of an object, you must explicitly refer to the object itself (unless you are using the deprecated with
statement).
In the example provided, you would utilize the name of the constant:
export const initialState = {
name: '',
acceptable: false,
identified: false,
variation: false,
variationText: () => {
return initialState.name.toUpperCase()
// ^^^^^^^^^^^^^
}
}
It's important to note that variationText
is not a method in your code, but rather an arrow function bound to a property. This distinction is crucial because if it were a method, you could potentially use this
in addition to referencing
initialState</code as shown above. However, arrow functions assigned to properties do not inherit <code>this
based on how they are called (More information available here).
If you were to convert it into a method and call it normally, you could employ this
:
export const initialState = {
name: '',
acceptable: false,
identified: false,
variation: false,
variationText() {
// ^^^^^^^^^^^^^^^^^
return this.name.toUpperCase()
// ^^^^^
}
}
Keep in mind that calling this method incorrectly might result in using the wrong this
; for further insights, refer to this explanation and here.