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

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

"An error has occurred stating that the header is not defined in

It is a coding issue related to payment methods. The headers type is undefined in this scenario, and as a newcomer to typescript, pinpointing the exact error has been challenging. An error message is indicating an issue with the headers in the if conditio ...

sending properties to dynamically loaded components

I'm struggling with transferring props between children and parent components using Vue Routes. Within my Layout component, I have a wrapper DIV structured like this: <template> <div class="container" v-bind:class="cssClass ...

Using AngularJS to implement modules in a single controller

Currently, I am in the process of learning Angularjs and have two separate template pages - one for login (login.html) and another for the main content (index.html). To incorporate a chart into my index.html page, I am utilizing a directive from here. Th ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

Using MongoDB map-reduce with Node.js: Incorporating intricate modules (along with their dependencies) into scopeObj

I am currently immersed in developing a complex map-reduce process for a mongodb database. To make the code more manageable, I have organized some intricate sections into modules that are then integrated into my map/reduce/finalize functions through my sco ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

Providing data in response to a completed form submission

As a beginner, I'm attempting to accomplish the following task: a user selects options from three dropdown menus within a form, and the chosen values are then sent to another file for processing. action="process.php" method="post" In the processing ...

Why is receiving input value in React not successful?

Attempted to retrieve input value when user clicks search, but encountered difficulties. var Login = React.createClass({ getInitialState: function () { return {name: ''}; }, handleSearch(){ alert(this.state.name); // Why isn't ...

Is it possible to manipulate a parent component's state with a child component?

I have been experimenting with Material UI's react modal to create a modal as my child component. In the parent component, I have set up a state that controls the visibility of the modal and added a button inside the modal to close it. However, this s ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

What is the best method for sending form data, specifically uploaded images, in Python Bottle with Ajax?

This form belongs to me <form method='post' enctype='multipart/form-data' id='uploadForm' name='formn'> <input type='file' value='' name='newfile'> <input type=&a ...

The React component continuously refreshes whenever the screen is resized or a different tab is opened

I've encountered a bizarre issue on my portfolio site where a diagonal circle is generated every few seconds. The problem arises when I minimize the window or switch tabs, and upon returning, multiple circles populate the screen simultaneously. This b ...

Updating form fields within nested forms using the FormBuilder array

The recommended method to change nested values according to the API documentation is using patchValue. For example, myForm.patchValue({'key': {'subKey': 'newValue'}}); But what if we need to change values in a nested array, ...

Angular9: construction involves an additional compilation process

After updating my Angular8 project to Angular9, I noticed a new step in the build process which involves compiling to esm. This additional step has added approximately 1 minute to my build time. A snippet of what this step looks like: Compiling @angular/ ...

Once the image is loaded, cropped, and displayed on the canvas, what is the best way to implement image rotation functionality for the user before converting it to base64?

My process involves cropping images to a square shape and drawing them onto a canvas. if(img.height >= img.width) { ctx.drawImage(img, 0, 0, 110, 110 * img.height / img.width); } else { ctx.drawImage(img, 0 , 0, 110 * img.width ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

"Experiencing difficulties deploying Firebase functions - Encountering an error message stating 'Cannot read property 'firebase-admin' of

I'm currently facing an issue during the deployment of my Firebase functions and I am seeking assistance to resolve it. While the deployment itself appears to be successful, I keep encountering the following error: Cannot read property 'firebas ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: with this new link: without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restriction of needing at least 10 reputation points in order to post more t ...

Handling multiple render calls and rerenders in React function components with setTimeout (best practice for firing multiple times)

Is there a way to optimize the Notification component in my App, so that the setTimeout function is only initialized once even if multiple notifications are pushed into the state? function Notification(props) { console.log("Notification function compone ...