What is the best way to access a variable from a class in ES6?

Hey there, I'm having trouble accessing the variable from the KeyCodeClass. Let me walk you through what I've tried so far: Attempt 1

class KeyCodeClass1 {
    constructor() {
        this.space;
    }
    KeyDown(e) {
        if (e.keyCode == 32) { this.space = true }
    }
    KeyUp(e) {
        if (e.keyCode == 32) { this.space = false }
    }
}

var KeyCode1 = new KeyCodeClass1();
window.addEventListener("keydown", KeyCode1.KeyDown, false);
window.addEventListener("keyup", KeyCode1.KeyUp, false);

setInterval(loop1,10);

function loop1() {
     console.log(KeyCode1.space);
}

Currently, my console is showing undefined. Even when I press the spacebar, which has a keycode of 32, the value remains undefined. To try and resolve this, I created a function to return the value: Attempt 2

class KeyCodeClass2 {
    constructor() {
        this.space;
    }
    KeyDown(e) {
        if (e.keyCode == 32) { this.space = true }
    }
    KeyUp(e) {
        if (e.keyCode == 32) { this.space = false }
    }
    Space() {
        return this.space;
    }
}

var KeyCode2 = new KeyCodeClass2();
window.addEventListener("keydown", KeyCode2.KeyDown, false);
window.addEventListener("keyup", KeyCode2.KeyUp, false);

setInterval(loop2,10);

function loop2() {
     console.log(KeyCode2.Space());
}

Still getting undefined in the console. In the third attempt, I initialized this.space in the constructor with either true or false: Attempt 3

constructor() {
    this.space = false;
}

Now, the console displays false. However, pressing the spacebar does not change it to true.

It got me thinking about whether the functions within the class are functioning properly. Here's an example to demonstrate that they are indeed working: Attempt 4

class KeyCodeClass4 {
    constructor() {
        this.space = false;
    }
    KeyDown(e) {
        if (e.keyCode == 32) {
            KeyCodeClass.space = true;
            console.log("space Down");
        }
    }
    KeyUp(e) {
        if (e.keyCode == 32) {
            KeyCodeClass.space = false;
            console.log("space Up");
        }
    }
}

var KeyCode4 = new KeyCodeClass4();
window.addEventListener("keydown", KeyCode4.KeyDown, false);
window.addEventListener("keyup", KeyCode4.KeyUp, false);

I am troubleshooting like this to enhance the readability and comprehension of my code. Any assistance you can provide on this matter would be greatly appreciated.

Answer №1

It appears that the current context may be getting lost, causing this to point to the window object instead of your class instance when your listeners are executed. One possible solution is:

var KeyCode = new KeyCodeClass2();
window.addEventListener("keydown", KeyCode.KeyDown.bind(KeyCode), false);
window.addEventListener("keyup", KeyCode.KeyUp.bind(KeyCode), false);

Feel free to try this approach and let me know if it resolves the issue for you.

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

A problem arises when the React effect hook fails to trigger while utilizing React Context

I have created a component that is supposed to generate different pages (one for each child) and display only the selected page: import * as React from "react"; export interface SwitchProps { pageId: number; children: React.ReactChild[]; } ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Error: req.body or req.params.id is not defined in the current context (PUT and PATCH requests)

I'm experiencing an issue where both req.body and req.params.id are returning undefined even though I am using express.json() before the app.patch. I have tried changing the route to /:id, but that did not resolve the problem. Interestingly, it works ...

Executing the slideToggle() function in JQuery with javascript

Trying to create a script that expands and collapses when users click on either the text or image. The image is a basic arrow that switches to an arrow pointing upwards when the div is expanded. The issue I'm facing is that the text disappears when t ...

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

React - Children components in an array not updating when props are modified within a callback function

The question may be a bit unclear, so let me provide further explanation. This is a personal project I am working on to improve my understanding of React basics and socket.io. Within this project, I have developed a CollapsibleList component and a NestedL ...

Guide to verifying the update of user information with sweet Alert on ASP MVC

I'm currently working on an ASP MVC web application that involves using stored procedures with SQL Server. My goal is to implement a confirmation alert (Sweet Alert) to confirm the data update for a logged-in user. The code for editing works fine wi ...

The switch statement within Angular returns null when using getElementById()

In my single page application, I am using ng-switch to switch between different 'pages'. One of these pages contains a modal that is opened using the following function: var modal = document.getElementById('myModal'); vm.openModal = fu ...

Ajax disregards the endless scroll material that has been injected into the DOM

I am currently facing an issue with loading posts on a page using foreach and the paginate function in Laravel. I have set up infinite scrolling through the posts, with each post having its own unique form. The first posts that load without JavaScript scro ...

Unveil as you scroll - ScrollMagic

I am working on a skill chart that dynamically fills when the document loads. I am exploring the possibility of using ScrollMagic to animate the chart filling as the user scrolls down. After trying various combinations of classes and pseudo-classes in the ...

Issues encountered with jQuery's $.ajax function when communicating with PHP

I am having trouble creating a simple app that displays data from a MySQL database using PHP and jQuery. The issue I am facing is with retrieving the data using jQuery. While my PHP script successfully returns the data without any problems, I am not receiv ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

The MongoDB operator "$in" does not recognize the type array that currently exists in the field

When attempting to execute an aggregate query in mongodb, I encountered an issue with the "$in" operator stating that the field passed is not recognized as an array. Here is the aggregate query being used: [ { '$match': { 'isVis ...

Similar to the reference of $(this) in jQuery, there is a similar concept in Vue.js

When working with jQuery, the use of $(this) allows for accessing elements without relying on classes or ids. How can we achieve a similar outcome in Vue.js? ...

Activate the Masterpage menu to emphasize its current state

I am currently utilizing the AdminLTE template on my website. One issue I have encountered is with the menu and its child menus. When redirecting to different pages using image buttons, the menu collapses back to its original state. While navigating throu ...

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

Transforming ASP.NET MVC IEnumerable view model into a JSON array of elements

My goal is to develop a dynamic calendar in ASP.NET MVC that pulls event data from a database to populate it. Right now, the calendar is set up to read a json array of objects, but I am facing an issue with converting my ViewModel data into a format that t ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...

Issues encountered when trying to use default color classes in Tailwind CSS

I'm currently working on a React project that utilizes the Tailwind CSS Framework. To integrate Tailwind into my React app, I used NPM to install it in the following way: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p After i ...