Accessing an array from another method within the JavaScript class

Hello everyone, I am new to JavaScript and have a question about calling an array from another function within the same class. Here is an example code snippet:

class Something {

  constructor () {}

  async functionA () {
       this.list = []
  }

  async functionB () {
       console.log(this.list)
  }

}

Answer №1

When creating a new object, you can define your variables using this.variableName, allowing other methods within the same class to access and modify these values. The variables can also be accessed from an instance of the class.

class Example {

    constructor() {
        this.items = []
    }

    async functionA () {
        this.items = [ 'apple', 'banana']
    }

    async functionB () {
        console.log(this.items)
    }

}

Answer №2

It appears your current approach is functioning properly...

class Example {
  constructor () {}

  async methodA () {
    this.collection = ['yes']
  }

  async methodB () {
    console.log(this.collection)
  }
}

const x = new Example();
x.methodA();
x.methodB();

https://codepen.io/username123/pen/randomlink123

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

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

How can I update the color of a list item when it is clicked within a foreach loop using knockout js?

Currently, I am encountering an issue with changing the color when a user clicks on a list item using the latest version of knockout js. My goal is to change the color of a list item when it is clicked and maintain that color until another item is clicked, ...

Is there a way to find a substring that ends precisely at the end of a string?

Looking to rename a file, the name is: Planet.Earth.01.From.Pole.to.Pole.2006.1080p.HDDVD.x264.anoXmous_.mp4 I want to remove everything starting from 2006 onwards. I considered using JavaScript string methods to find the index of the unnecessary part an ...

Can you explain the distinction between utilizing Object.create(BaseObject) and incorporating util.inherits(MyObject, BaseObject)?

Can you explain the difference between these two methods of setting the prototype? MyObject.prototype = Object.create(EventEmitter.prototype); MyObject.prototype = util.inherits(MyObject, EventEmitter); UPDATE I've noticed in various projects that ...

Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format. These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below: OBJ 1 { "data":{ "IRBs":{ "n ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

How can React.Js and Typescript be used to extract information from JSON files?

Hi there! I've been working with MongoDB, Mongoose, and React.Js for my project. One of the features I have is a page where users can view posts. When making a fetch request to the backend, I receive JSON data in response: { "post" ...

Matching list symbols in regular expressions (Angular 2)

I have been attempting to find a solution for matching a list of symbols using regex, but I keep encountering errors in the result. The symbol list includes: !@#$+*{}?<>&’”[]=%^ if (text.match('^[\[\]\!\"\#&bs ...

Exploring the magic of VueJS: Implementing computed properties for "set/get" functionalities in tandem with Vue.Draggable and

Currently, I am in need of assistance with utilizing "Vue.Draggable". For the past two days, I have been struggling to properly update the draggable array. The main challenge lies in: Updating the draggable array using computed set/get functions Obtaini ...

I am experiencing issues with my React DND implementation in Next JS - can anyone help troubleshoot?

I'm encountering an issue with my React DND implementation. Although I am able to drag elements, they are not being received by the drop targets. I even tried using console.log in the drop function of useDrop but nothing is logging in the console on d ...

Browser now replacing attribute translate="yes" with translate="translate"

We have encountered an issue with a translation library that is affecting the functionality of our page. <html lang="en" class="notranslate translated-ltr"> <meta name="google" content="notranslate"> As ...

Attach an event listener to the HTML content

Being new to Javascript, I am attempting to add an event listener for each button on every card. However, the code seems to only apply the event 'click' to the last card (button). Is there a way to make this work with the innerHTML of the card? l ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

Troubleshooting: Else block not functioning as expected within a React JS map function

I have a notification feature that makes an API call every 10 seconds to display an alert based on the response. However, I'm encountering an issue where the div is not being rendered properly. The div should be displayed based on certain conditions w ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

Discovering HTML attributes using part of the attribute's name

Can someone help me identify and remove all attributes in my HTML page that contain the word "data"? I want to clear out the values for these attributes. Any suggestions on how to achieve this? For instance, consider the following snippet from my HTML: & ...

Merge the elements of an array to form a clickable hyperlink

Hello everyone, I have encountered an issue. I created a wishlist that outputs the results as an array with the selected values. Here is an example: Array ( [product_name] => 1 [Testartikel 1] => 2 [Testartikel 4] => 5) The current output is not ...

How can I dynamically remove an option from a select dropdown if it already exists in another option using jQuery?

In order to achieve the desired functionality, I need to dynamically adjust the select options based on user input. Additionally, I want the selection to update automatically upon a change event. var dynamicCount = 1; $('#add').click(function ...

Unable to pass data to the onChange event for the material-ui datePicker components

Need help with a form that includes a material-ui DatePicker. Here is an example: <DatePicker name="startDate" autoOk={true} floatingLabelText="startDate" onChange={(x, event) => {console.log(arguments);}} /> When I change the date, the console ...

Dynamic JavaScript tool

Does anyone know which library is being used on the website linked here? I am working on a project similar to this and would appreciate if anyone can identify this library for me. Thank you in advance. ...