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

Is there a way to differentiate the color of an active link from an inactive one, so users can easily identify which link they are currently viewing?

How can I customize the color of text for the active page on my website's sidebar? For example, I have two hyperlinks, one for HOME and one for ABOUT. When a user clicks on the HOME link, I want the text color to change to green while the ABOUT link r ...

What is the best way to integrate Bootstrap 5 with Next.js?

After adding Bootstrap to my project with npm install bootstrap, I included the style in /pages/_app.js like this: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Component, pageProps }) { return <Component {...pag ...

Sending the results from a Vue.js component to a text input field in HTML

Using vue.js and the v-for function to read QR codes has been a challenge for me. For example: <ul v-for="(scan,key) in scans" :key="key" > {{scan.content}} </ul> I need to extract the value inside {{scan.content}}, like an EmployeeID, but I ...

Concealing URL in client-side fetch request within Next.js

A contact form built in Next.js makes use of the FormSubmit API to send emails upon clicking the submit button. Below is the code for the onSubmit handler: const handleSubmit = async (e) => { e.preventDefault(); const res = await fetch("https:/ ...

Trouble with bringing in the solana/web3.js library

After successfully importing the solana/web3.js package and running it within a NodeJS file, everything was working fine. However, things took a turn when attempting to connect this file with basic HTML, resulting in an error being thrown. import { Tra ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Prisma encountered an error with the database string: Invalid MongoDB connection string

I'm encountering an issue with my MongoDB data provider, as I am informed that my connection string is invalid. The specific error message states: The provided database string is invalid. MongoDB connection string error: Missing delimiting slash betw ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

utilizing different types of text style

Whenever I write a paragraph, I want the text to be styled like this: Click here for alt text http://img6.imageshack.us/img6/9894/fullscreencapture282010.jpg Do I need to use CSS to achieve this kind of formatting? I'd like it to look similar. ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

Retrieve various URLs within an object using React

My task involves extracting all URLs from a specific object. Object { "Info": "/api/2", "Logo": "/api/2/Logo", "Photo": "/api/2/photo", } I aim to store the responses in a state, ensuring t ...

How to Retrieve Upload Progress via HTTP Request in PHP

Is there a way to monitor the progress of file uploads by accessing the HTTP request in PHP? If so, how can this be achieved when uploading files into a MySQL database? require('../connect_db.php'); //Collect all necessary data $name = $dbc-> ...

Unwanted transparency issue in MaterialUI (MUI) BottomNavigation

Greetings fellow hobby developer! I recently embarked on a project using create-react-app and incorporated MUI dependencies. One feature I added was a fixed BottomNavigation, which you can view in action here. Interestingly, in CodeSandbox, the BottomNavi ...

AngularJS radio button slider with ng-model and ng-checked functionality

I'm facing an issue where my ng-model is not getting updated when I cycle through radio button images using arrows instead of clicking on the image. How can I resolve this? HTML <div ng-repeat="contact in contacts" ng-show="showContactID == ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

Experiencing a bug in Express, unable to dispatch the request

controllers/userController.js import User from '../models/userModel.js' import asyncHandler from 'express-async-handler' import generateToken from '../utils/generateToken.js' // @desc Authenticate user & obtain token / ...

The error message "Create controller with service — Get... is not a function" indicates that

Within my ASP.NET Boilerplate project, the following code snippet is present: (function () { appModule.controller('augustinum.views.kostenstelle.index', [ '$scope', '$uibModal', 'abp.services.app.kostenstelle ...

"Encountering difficulty in importing the graphql node package with the import keyword

Could you please clarify this for me? Whenever I attempt to bring in the graphql node package using the import keyword, the imported module is recognized as undefined. However, if I utilize require, the module imports correctly. Interestingly, other node ...

Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1 On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1 This is the JavaScript code I have: const express = req ...

Transmitting information via Ajax, jquery, Node.js, and Express

Seeking assistance as I struggle to comprehend the process while trying to implement it based on various online resources. My carousel directs users right after signing up, and I aim to gather information about their profile through simple input questions. ...