Utilizing "this" correctly within JavaScript objects

Can someone help me understand how to access enums.ROCK within the prop in the code snippet below? I keep getting an error that says

Uncaught TypeError: Cannot read property 'enums' of undefined
. Please pay attention to the comment ERROR LINE.

const app = {
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    DEFAULT_USER_CHOICE: this.ROCK //default, remember this keyword
  },
  prop: {
    isGameRunning: false,
    mySelection: this.app.enums.ROCK //ERROR LINE
  }
};

I've attempted using mySelection: app.enums.ROCK, which resulted in the error

Uncaught ReferenceError: Cannot access 'app' before initialization
.

Click the following links for examples:

Sample 1: https://jsfiddle.net/5zp7yode/

Sample 2: https://jsfiddle.net/5zp7yode/1/

However, the following example works perfectly fine:

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

alert(person.fullName());

Sample 3: https://jsfiddle.net/0o93afLq/

I also tried the following approach without success:

const app = {
  self: this,
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    DEFAULT_USER_CHOICE: this.ROCK //default, remember this keyword
  },
  prop: {
    isGameRunning: false,
    mySelection: self.enums.ROCK
  }
};

alert(app.prop.mySelection);

Sample 4: https://jsfiddle.net/x89kj2zn/

I also have a working solution using a function but facing issues calling it inside the prop:

const app = {
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    DEFAULT_USER_CHOICE: this.ROCK //default, remember this keyword
  },
  prop: {
    isGameRunning: false
  },
  getMySelection: function(){
    return app.enums.ROCK;
  }
};
alert(app.getMySelection());

Sample 5: https://jsfiddle.net/v5qzdx3s/

Answer №1

To access values, you can utilize the get method.

const website = {
  types: {
    SPORTS: 'SPORTS',
    MUSIC: 'MUSIC',
    MOVIES: 'MOVIES',
    get DEFAULT_TYPE(){
      return website.types.SPORTS
    }
  },
  details: {
    isActive: true,
    get category(){
      return website.types.SPORTS
    }
  }
};

console.log(website)

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

Retrieve the binary file data that was sent via Postman using Node.js/Express.js

I am currently testing file uploading in my backend system. I am using Postman to send binary data as a file in the request body, and now I need to extract this data from the POST request. req.body The above code snippet returns a binary buffer that look ...

Identify input elements that specifically contain an onclick event

Several of the input elements on my page have a function called setSomeFunction() that either shows or hides certain divs when clicked. I know I can locate all the input elements using document.getElementsByTagName("input") and store them in an array. How ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

Unable to retrieve the value stored in the global variable

I recently updated my code to use global variables for two select elements in order to simplify things. Previously, I had separate variables for values and innerHTML which felt redundant. Now, with global variables like user and group initialized at docum ...

Animation for Images in Angular v1.2

After reviewing tutorials and previous questions, I have been trying to pinpoint where my code is going wrong in applying an animation to transition between the images I want to display. The ng-show function effectively displays the selected picture, but ...

halt execution of npm test and erase any printed content

When I run npm test on my React project, it runs unit tests using jest and react testing library. The test logs (including console log lines added for debugging) are printed to the screen but get deleted after running the tests. It seems like the logs are ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

Is there a comparable solution like Fabric in Javascript or Node.js?

One thing that I really appreciate about Fabric is how it simplifies the deployment process to multiple servers, especially with its strong support for SSH. But since our project is based on node.js, it would be ideal if we could achieve a similar function ...

What is the reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Prevent ng-click functionality from activating when clicking on a link inside an external element

I am facing an issue on my website using ui-router. I have a table with ng-click set on the cells, but there are links inside the cells as well. My goal is to disable the ng-click when the link is clicked. <div ng-click="click()" style="background: #d3 ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

Trouble arises when adding a .js script to the webpage

I'm feeling quite puzzled by this small piece of code, as it appears to be the simplest thing you'll come across today. Despite that, I can't help but seek guidance because I've been staring at it for what feels like an eternity and can ...

Steps to eliminate a specific value from an array

I need to remove values with the .html extension from an array in JavaScript, leaving only those items that do not have the .html extension. Here's my current code: main.js: var arr=["test1.html","power.html","main.html","save.md","kart.html","taste ...

Navigating through Node and Express on Azure App Service

I'm facing an issue that I am not sure if it is related to Node or Azure App Service, so here's the situation: In my Node/Express app, I have defined two routes: router.get("/users", checkAuthHeader, userController.getUsers); router.po ...

Establish a connection between servers operating on two distinct ports

I'm completely new to JavaScript and developing web applications. I have set up two servers on my computer running on separate ports (5000 and 5001). The server on port 5000 needs to communicate with the one on port 5001, but I'm struggling to g ...

The URL provided for the Ajax HTTP request is not accurate

Consider the following JavaScript code: <script type="text/javascript" charset="utf-8> function goForLogin() { var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","/account/login",true); xmlhttp.s ...

Tips for sending query string parameters to an AJAX request using data

Currently, I am making an ajax call to hit the API and I need to include a query parameter. How can I accomplish this with my ajax call? Below is the code snippet that I am using. Any assistance on this matter would be greatly appreciated. Thank you. ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

Is there a way to remove the initial number entered on a calculator's display in order to prevent the second number from being added onto the first one?

I am currently in the process of developing a calculator using HTML, CSS, and JavaScript. However, I have encountered an issue with my code. After a user inputs a number and then clicks on an operator, the operator remains highlighted until the user inputs ...