Object array containing function objects

I'm currently working on implementing a model in JavaScript in an object-oriented manner. I have an object X that contains several functions, and I would like to create an object array "in X" where some of its fields reference functions within X. Here's an example of what I've attempted:

function X(){
    this.open = function(e){...};
    this.run = function(e){...};
    this.close = function(e){...};
    //...

    this.STATES = {
        1: {name : "opening", applyAction : this.open},
        2: {name : "running", applyAction : this.run},
        3: {name : "closing", applyAction : this.close},
        //...
    };

    this.currentState = this.STATES[1];

    //...

    this.update = function(e){
        //...
        currentState.applyAction(e);
        //...
    }
}

Unfortunately, this approach is not functioning as expected. I am struggling to identify the issue, so if you have an alternative method for achieving the same outcome, your suggestions are greatly appreciated.

Answer №1

The issue with this code is that the instance of 'this' is referring to the literal object being defined, rather than the intended 'this':

this.STATES = {
    1: {name : "opening", applyAction : this.open},
    2: {name : "runing", applyAction : this.run},
    3: {name : "closing", applyAction : this.close},
    //...
};

One way to resolve this is by using a variable like 'self' to maintain the correct scope:

function X() {
    var self = this;

    this.open = function() {
        // ...
    }

    this.STATES = {
        1: {name: "opening", applyAction: self.open},
        ...

It may also be helpful to brush up on Javascript scoping rules.

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

What is the best way to extract the URL value and insert it into a text box?

After submitting the form, the URL looks like this: from=Paris%2C+France&to=Rome%2C+Italy On the new page, I need the value of 'from' to be inserted into the following input field: <input id="from" class="form-control" type="text" name= ...

The JSON array data is coming back as undefined

Currently facing an issue with the data sa var data = '[{"idcoupons_tbl":"1","discount_percent":"10"}]'; Every time I attempt to parse and retrieve a discount_percent, ie var result= jQuery.parseJSON(data); alert(result["discount_percent"]); ...

Jest test failing due to issues with a stateful React component containing an asynchronous function

I'm currently going through a Jest testing tutorial on Pluralsight that can be found here. Even though I have written the code exactly like the author, my test is not passing for some reason. Link to my Pull request on the author's repo: https:/ ...

Nuxt.js ERROR: Unable to find reference to 'window' object

Currently working with Nuxt.js and encountering an issue while configuring vuex-persist. Seeking assistance from someone familiar with this problem. store/index.js store/LangModule.js ...

Detecting the clicked link within a React component

My NavBar features a Logo that includes a Link to the Home page "/". The application kicks off from the main page and as per user selections, the UI will adapt accordingly. To offer users a chance to reset everything if they are currently on the Home compo ...

Automatically relaunch NodeJS application upon app failure

I am looking for a way to automatically restart my NodeJS (Express) app after crashes with errors. I am familiar with the forever npm package, but all the examples I found were for running the app in development. My goal is to implement this in production ...

How can I send an Array to a JQuery Ajax Post request?

I am faced with a challenge involving a form containing the following elements: <input type="text" class="attr_values[]" value="1" /> <input type="text" class="attr_values[]" value="2" /> My goal is to pass all the values stored in the "attr_ ...

Access an array element based on its value

Apologies for the odd phrasing, but I'm unsure of the correct terminology for this. I currently have an array that looks like this: [#<Item:0x007faeea066508 @name="Backpack", @exam="Not much here... just a backpack">] Essentially, this array r ...

Testing a Jest jest by mocking the creation of an object

Recently, I came across a piece of code that I needed to test before making any changes. However, I encountered an issue where I couldn't mock the controller's call to new dao(). //controller.js const dao = require('./dao'); exports.ca ...

Discover the method to retrieve the month name from an HTML Date input value

Here we have a date input field <input id="customer-date" name="customer-date" type="date" required> Accompanied by this script const customerDate = document.getElementById('customer-date').value; const dateHandler = document.getElementB ...

Can you provide an example of a basic JSON structure that defines a payment transaction using PayPal?

I need a JSON example that defines a simple PayPal donation, specifically including parameters for a payment date and an option to set the donation as recurring annually. This isn't covered in the official PayPal documentation. I've attempted the ...

How can I pass a DOM element as a prop in Vue 3?

As someone who is brand new to Vue, I'm exploring the possibilities. Although it's not something I typically do, I believe achieving a similar outcome in React + JSX (untested) could look like this: render() { const el = <p>Blah <a hre ...

Exploring data visualization within a JSX Component

I am attempting to dynamically render a Card component that is mapped from an array of objects. However, I am encountering an "unexpected token error" and the URL is not rendering as expected. The goal is to display five cards based on the data within the ...

Having issues transferring values from one page to another. Any suggestions to make it work correctly?

I currently have two pages within my website, one is called details.page and the other is maps.page. In the details page, I have set up a search input as shown below : <form method="get" id="form-search" data-ajax="true" action="maps.page"> ...

transforming an array of strings to double values using a .csv file input

Currently, I am working on processing a .csv file that consists of strings and converting the data within a specific range to type double. My main objective is to extract the 4th column, but it seems more practical to process everything as a matrix in case ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

Limiting the length of numbers in Material UI

Is there a way to restrict user input to only numbers with a maximum length of 3 in Material UI? <TextField id="score" label="score" className={classes.textField} name="totalScore" margin="normal" defaultValue={score} /> We specifically ...

What is the process for changing colors once vertex colors have been updated?

Explaining the issue with an example. I have included a brief snippet of HTML code here to demonstrate the problem. In this scenario, I have created a simple triangle geometry as a global variable. By clicking the "Red" button, function red() is invoked ...

Ways to create a looping mechanism with specified number restrictions and limitations

Can anyone assist me with this problem? I am looking to create a "looping" effect similar to the image provided. What is the logic behind this repetition? Thank you in advance for your help! Here is an example output: ...

Incorporating a fresh attribute into a javascript object

We start with an array that includes the following data structure: array = [{ key: '2001', values: [ { id : '123a', points: 3, hours: 3 }, { id : '123a', points: 4, hours: 2 }, { id : '4444', points: 3, hour ...