What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply returns the function itself.

My attempts thus far have led me to scouring the internet and Stack Overflow in search of a resolution. However, I have been unsuccessful in finding a suitable solution or deciphering the ones I have come across. It seems that the concept of "closures" might play a role here, as most recommendations involve returning from the submethod and subsequently returning the submethod from the parent method. Unfortunately, each time I have tried implementing these suggestions, I encountered numerous errors - whether it be an undefined submethod or the continued output of a function. The presence of multiple methods might be complicating matters further.

In the realm of context, I am currently in the process of developing a platformer game that features various iterations of the same enemy type. My objective is to conduct collision checks between the player character and the enemy's weapon, necessitating the extraction of certain values from the enemy function (I refrain from using the term "class", although I am unsure if this is the correct terminology). Being more well-versed in Java, the inability to easily create a separate class with a method for retrieving values is proving to be a source of frustration.

//assume all the other html/main stuff is already set up
var temp = {
  create: c4,
  update: u4
}
MyObject = function(value) {
  this.value = value; //passed in value
  var magicNumber = 4; //local value initialized/declared

  this.valueChecker = function() {
    //return boolean
    return this.value == this.magicNumber;
  }

  this.otherValueChecker = function() {
    //return boolean
    return (this.value + 1) == this.magicNumber;
  }
}

//just make the space bar tied to a boolean
var someKeyPress;

function c4() {
  someKeyPress = game.input.keyboard.addKey(Phaser.Keyboard.A);
}

var someObjects = [];
//... later on in the program, presuming key already coded
function u4() {
  //add a new MyObject to array someObjects
  if (someKeyPress.isDown) {
    //check with various random numbers between 3 to 5
    someObjects.push(new MyObject(game.rnd.integerInRange(3, 5)));
  }

  //run through MyObject(s) added to someObjects, and see if any match number
  for (var i = 0; i < someObjects.length; i++) {
    console.log(someObjects[i].valueChecker);
  }
}



/* current output
    ƒ () {
        //return boolean
return this.value == this.magicNumber;
}
    */

Answer №1

Give it a shot

console.log(someObjects[i].checkValue())

I believe that the value checker acts as a function

this.checkValue = function() 

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

The code begins executing even before the function has finished its execution

I believe that is what's happening, but I'm not entirely sure. There's code in a .js file that invokes a function from another .js file. This function performs an ajax call to a php page which generates and returns a list of radio buttons wi ...

Tips for rearranging table columns using drag and drop in react js

I have been experimenting with various libraries to create a drag-and-drop feature for changing table columns order. Here is my current implementation: import React, { useState } from 'react'; import './list_de_tournees.css' const Table ...

What steps can be taken to resolve the issue of Ajax not retrieving any data from

I'm struggling to identify the error in this code. I have created a search bar and implemented AJAX to automatically fetch data. Here is the HTML file: <!DOCTYPE html> <html> <head> <title></title> <script ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

Is dynamic data supported by Next.js SSG?

I'm currently developing a web application with Next.js and I need clarification on how Static generated sites work. My project is a blog that necessitates a unique path for each blog entry in the database. If I were to statically generate my web appl ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Having trouble with Material-UI Textfield losing focus after re-rendering? Need a solution?

I am currently utilizing Material-ui Textfield to display a repeatable array object: const [sections, setSections] = useState([ { Title: "Introduction", Text: "" }, { Title: "Relationship", ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US nu ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

Generating requests using ExpressJS

Is it possible to send a POST request using a GET action? Although everything seems to be working fine, the "TOKEN" does not appear after the post. I am puzzled as to why this is happening. const request = require('request'); exports.g ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server th ...

"Drag and drop elements that automatically snap to a grid and move with

I'm trying to create a small, square div that follows the mouse cursor, but I want it to snap to a 3x3 pixel grid. Here is what I have so far: $(document).mousemove(function(e) { window.x = e.pageX; window.y = e.pageY; if(window.x % 9 === 0 ){ ...

When using promises in Vue, you can expect to receive an observer object

In my Vue.js project, I am trying to trigger a Vuex action in the created() lifecycle hook and then proceed to call an asynchronous method to fetch more data from the server upon receiving the initial data. The goal is to utilize this data in a component ...

Utilizing Jquery tabs for consistent height display

Currently, I am utilizing jquery tabs for showcasing various content. This is what my functions look like: $(function() { $( "#tabs" ).tabs(); }); I attempted to ensure all tabs have the same height by using this approach: var heightStyle = ...

ASP.NET MVC - AjaxContext is a powerful feature provided by the

I recently attempted to delve into the AjaxContext utilized by ASP.NET-MVC in scenarios such as Ajax Actionlinks and their clientside functions like onSuccess and onComplete. However, I must admit that I found it quite confusing... Is there any documentati ...

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...