Is it possible for a method within a class to retrieve properties from a different object within the same class?

I'm facing an issue with accessing the necessary object properties within a method. In my scenario, I have a Game class that generates a new game object. Once the object is created, I attempt to execute the draw method. This draw method requires information from state.house.color, but I'm struggling to find the correct way to access it because using "this" inside draw does not reference the game object. I've used .bind(this) previously, but it doesn't seem to work in this case as I need to bind an object rather than a function. Any advice would be greatly appreciated!

class Game {
    state = {
        house: {
            color: "blue"    
        }
    }
    assets = {
        house: {
            draw(){
                //some logic here like console.log(this.state.house.color)
            }
        }
    }
};

let testGame = new Game();

testGame.assets.house.draw();

Answer №1

If you're looking for a solution to your issue, consider utilizing arrow functions in JavaScript. They are a great way to prevent the override of the this keyword.

class Game {
    state = {
        house: {
            color: "blue"    
        }
    }
    assets = {
        house: {
            draw: () => {
                console.log(this.state.house.color);
            }
        }
    }
}

let testGame = new Game()

testGame.assets.house.draw();

Another option is to use the bind method, although it may not be as optimal in this scenario:

class Game {
    state = {
        house: {
            color: "blue"    
        }
    }
    assets = {
        house: {
            draw() {
                console.log(this.state.house.color);
            }
        }
    }
}

let testGame = new Game()

testGame.assets.house.draw.bind(testGame)();

Answer №2

Instead of creating a nested arrow function or bound function within the .assets.house.draw property, it is better to keep properties top-level in a class instance without trying to namespace them.

If necessary, consider creating a separate class:

class House {
    constructor(color) {
        this.color = color;
    }
    draw() {
       console.log(this.color);
    }
}
class Game {
    house = new House("blue");
}

const testGame = new Game();
testGame.house.draw();

Ensure to pass anything that the house requires from the game into its constructor.

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

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

Attempting to use express and nodemailer to send an email, but there is absolutely no output appearing in either the console or the terminal

When I click the send email button, it should send the data to a mailhog inbox. However, nothing happens - no errors in the console or terminal. My goal is to use nodemailer to send the name, email, chosen plan, and message from the form to the mailhog add ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Ensuring the accuracy of URLs using JavaScript

I am developing a form with an input field for entering a URL and a submit button. I want to incorporate JavaScript validation to show an alert box when a correct URL is entered. Is it achievable using JavaScript? If so, can you please guide me on how to i ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

What causes duplicate packages to appear in Bower at times?

There appears to be two identical packages available for the Sugar javascript library, sugar and sugarjs. Are these packages interchangeable or are they being maintained separately by different individuals? ➔ bower info sugarjs bower sugarjs#* ...

The IIS URL rewrite is causing issues with the rewriting of CSS and JS files

Struggling with my URL rewrites - every time I set up a rewrite for a page, it ends up affecting the CSS and JS files linked within the webpage, resulting in them not displaying properly. In an attempt to fix this issue, I tried using fully qualified path ...

Discover the secrets to acquiring cookies within a Next.js environment

I am currently working with Next.js and attempting to retrieve a cookie value. Below is the code I have written: import cookie from "js-cookie"; export default function Home({ token }) { return ( <div className="flex flex-col items ...

Organizing layers with Leaflet's layerGroup controls

I am working with a series of Leaflet FeatureGroups, each made up of GeoJSON layers. These FeatureGroups have similar concepts but need to be kept separate for control purposes. I also require the ability to toggle all FeatureGroups on and off simultaneous ...

Arranged Items according to the value of nested objects

Sorting an object based on the number of votes it has and then mapping over the sorted object can be a bit tricky, especially when trying to retain the original keys. const data = { "comment-1508872637211" : { "description" : "Blah", "votes" : 1 ...

Using a set formatter in jqGrid within a personalized formatter

Can I incorporate a predefined formatter into a custom formatter? Here is an example using the colModel: colModel: [ ... { name: 'col1', formatter: myFormatter } ... ] Below is the custom formatter function: function myFormatter(cellVal ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Error encountered while attempting to install ungit on Windows XP: Unable to locate file directory in C:/Documents

Ungit seems like the ideal tool to gain a better understanding of git, thanks to its graphical interface that simplifies the process. I came across this video explanation which is very helpful in grasping how git functions, even if you don't intend to ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...