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

Triggering an error message when a user attempts to submit an incomplete angular form

Working on an Angular form where users advance to the next step by clicking a button, but it remains disabled until all fields are valid. I'm wondering how I can implement a custom class to highlight incomplete fields when the user tries to move to t ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Can you group polygons in layers using Phaser?

My goal is to animate two polygons: one that remains stationary and another that changes shape while moving. The challenge is to ensure that the stationary polygon always stays on top when overlapping. This is my proposed solution: (function() { "use ...

Guide to displaying database results in an HTML dropdown menu by utilizing AJAX technology

Greetings! As a newcomer to the realms of PHP and AJAX, I am currently on a quest to showcase the outcomes of a query within an HTML dropdown using AJAX. Let's delve into my PHP code: $pro1 = mysqli_query("select email from groups"); I made an attemp ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

Steps to trigger a JavaScript popup from an iframe window to the parent window

Currently I am developing a web application using JSP with JavaScript. Within the parent window, an iframe is being utilized. The issue arises when a button in the iframe page is clicked, as it opens a popup window within the iframe itself. However, my obj ...

Converting Persian calendar date to Gregorian in JavaScript

Looking for assistance in converting a date from 1379/10/02 to AD format, specifically to the date 2000/4/29 using the momentJs library. Any help with this task would be greatly appreciated. Thank you! ...

The icon in Material UI button is missing from the display

The button is functional, but the icon inside it isn't displaying correctly: Here is the code for the button: <Button color="secondary" aria-label="add an alarm"> <AlarmIcon></AlarmIcon> </Button> <But ...

Performing a series of synchronous JavaScript calls in Node.js by executing GET requests within a for loop

I'm utilizing super-agent in node to interact with a public API and I'm curious if there's a way to make synchronous calls using it. Although I appreciate its automatic caching feature, my research online suggests that synchronous calls are ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Encrypt JavaScript for a jade layout

I need to find a way to successfully pass a .js file to a jade template in order for it to display correctly within an ACE editor. However, I am encountering errors when attempting to render certain files that may contain regex and escaped characters. How ...

What is the most effective method to avoid duplicating elements in the DOM tree?

Seeking a solution for appending a span element to the DOM. if (check something...) { const newSpan = createElement('span'); newSpan.id = '_span'; const container = document.getElementById('container'); conta ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

using async/await to retrieve data from a Google spreadsheet in Node.js

How can I use a for-loop to iterate through sheets in a Google spreadsheet and access specific cells within each sheet? I have a Google spreadsheet with Sheet1, Sheet2,... , Sheet5 where the cell values are Value1,..., Value5. The expected result should be ...

Executing a Javascript function using ssl

As a newcomer to SSL and Javascript, I hope you'll pardon any lack of knowledge on my part. I've been trying to research my question online, but haven't had much luck finding the answer. Context In simple terms, my website has a subdomain ...

What is the best way to extract data from a series of nested JSON objects and insert it into a text field for editing?

I am facing a challenge with appending a group of nested JSON objects to a text field without hard coding multiple fields. Although I have used the .map functionality before, I am struggling to make it work in this specific scenario. const [questions, setQ ...

How can I assign a prop to a component within the root layout in Next.js version 13, especially when the root layout is required to be a server-side component at all times?

I need assistance with a project I'm working on. My goal is to create a SongPlayer component in Next.js version 13 that plays music and is positioned at the bottom of the window, similar to Spotify's player. However, my SongPlayer component requi ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...