Retrieve information about an object's properties by calling methods on the object itself

Let's say we have a json object structured like this;

export const initialState = {

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


//You can use it in a way that merges the item's properties with initialState, keeping any missing attributes or methods intact.
return {...initialState, ...item}

But when trying to access the attributes within the method, they are not available.

Thank you.

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving a JSON object based on its name

Here is the structure of a JSON object I am working with: [ { "filters": [ { "name": "category", "list": [ { "category-abc": { "title": "abc", "number": "2" ...

Can you please tell me the event that is triggered when an option is unselected in Vue.Drag

I am trying to figure out the event for selecting an item since I already know about the "choose" event. However, I am uncertain about what to use for un-selecting an item. In my particular case, I am unable to utilize the @end event. <draggable :list= ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Encountering a surprising token error while running a node.js application with a classic example

I downloaded node.js from its official website and followed the instructions provided here. I attempted to run the example code snippet from the "JavaScript - The Good Parts" textbook: var myObject = { value: 0; increment: function (inc) { this.value ...

Experience the classic game of rock-paper-scissors brought to life through JavaScript and HTML,

I've been working on a rock, paper, scissors game in JavaScript and I'm struggling to get the wins and losses to register correctly. The game keeps resulting in a draw even though I've checked my code multiple times. It's frustrating be ...

Validation of React Input for empty values or numbers

Looking for assistance with improving my method for checking the state of the calculator input and determining if it is empty or not. Here are the two issues I need help with: Is there a more elegant solution to incorporate a validation check to ensure ...

Steps for Setting the Value of a Dropdown Option Based on its Unique Identifier

<select id=workTypeSelection> <option id="-1">-Select a Work Type-</option> <option id="1">Common</option> <option id="3">Computer Maintenance</option> <option id="5">Facility Maintenance</ ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

Unconventional login processes showcased in Redux-Saga's documentation

When looking at the login flow example in the redux-saga documentation, it is clear that the expected action sequence is well-defined. However, does the LOGOUT action always follow the LOGIN action? In real-world scenarios, such as when a user's sessi ...

Is it possible to access a PHP array file from a server using JSON in JavaScript for data visualization?

I am currently attempting to access a .php file on a server through my Netbeans software using JavaScript with JSON. As a beginner, I have been struggling to find a solution to this issue. Within the developers tool, I am encountering the following error ...

I encountered an issue with passing arguments in the invoke function I redesigned

I am currently attempting to replicate the functionality of the .invoke() function. Although I can successfully call the function, I am facing difficulties when it comes to passing arguments. I have made attempts using call and apply, but unfortunately, I ...

Create a unique functionality by assigning multiple event handlers to a single event

I am looking to add a JavaScript function to an event that already has a handler function. The new function should complement the existing one rather than replace it. For instance: There is a function named exFunction() that is currently linked to docume ...

Creating HTML code with TinyMCE

Currently, I have integrated TinyMce into my asp.net website for posting comments. Ensuring the safety of input data before inserting it into the database is crucial to me. TinyMce performs its own HTML encoding on the client side. However, advice fro ...

What is the process for connecting a control in a template to an event listener?

I've inserted a tag into several components in my template like so. <div>...</div> <div #blopp>...</div> <div>...</div> <div #blopp>...</div> <div #blopp>...</div> <div>...</div> ...

Launching Node Application

While working with NestJS and IIS, I encountered an issue when deploying my 'dist' folder on the server using IISNode. The error message 'module not found @nestjs/core' prompted me to install the entire 'package.json' files (n ...

What could be the reason behind the failure of Google Place API integration?

When I try to access the JSON data from the provided link, it works fine. However, when I integrate it into our project, there seems to be an issue. Link to JSON Data ...

How to send and download files using Express.js and React on the client side

Currently, my backend is built with Express JS and the frontend with React JS. In certain routes, I need to send a file in response to requests. Here's how I'm currently handling it: return res.status(200).sendFile(path.resolve(`files/${product. ...