What is the best way to retrieve a variable from an object?

Struggling to access pubOuter and keep getting undefined. Can anyone help me with this issue? I can't seem to pass outer from the inner2() function. Maybe I'm overlooking something obvious. Thanks in advance.

Javascript

var myObject = (function(){
   var outer;

   function inner1(IN_number){
     outer = IN_number*2;
   }

   function inner2(){
     inner1(10);
     return outer;
   }


   return {
     pubFnInner1: inner1,
     pubFnInner2: inner2,
     pubOuter:    outer
   };

})();

$("#click").on("click", function(){
   console.log("outer" + myObject.pubOuter);  
});

HTML

<button id="click">Click</button>

Answer №1

Successfully accessing the putOuter property is now within reach. The only hurdle to overcome is its lack of initialization before usage.

To address this issue, I have made changes to the code by setting outer to 1 from the get-go. This adjustment ensures that when multiplied by IN_number in the inner1 function, it no longer yields a value of NaN.

var myObject = (function(){
   var outer = 1;

   function inner1(IN_number){
     outer = IN_number*2;
   }

   function inner2(){
     inner1(10);
     return outer;
   }


   return {
     pubFnInner1: inner1,
     pubFnInner2: inner2,
     pubOuter:    outer
   };

})();

$("#click").on("click", function(){

   console.log("outer" + myObject.pubOuter);
   myObject.pubFnInner1(10);
   console.log("outer" + myObject.pubOuter);

   // Alternatively, consolidate both steps by utilizing your pubFnInner2 method.
   console.log("outer" + myObject.pubFnInner2());
});

Answer №2

pubOuter remains undefined due to the assignment of outer, which itself is undefined because the function inner1 is never executed. To resolve this issue, follow these steps:

var myObject = (function(){
   var outer;

   function inner1(IN_number){
     outer = IN_number*2;
   }

   function inner2(){
     inner1(10);
     return outer;
   }


   return {
     pubFnInner1: inner1(),
     pubFnInner2: inner2(),
     pubOuter:    outer
   };

})();

$("#click").on("click", function(){
   console.log("outer" + myObject.pubOuter);  
});

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

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Best practices for storing non-reactive and static data in a Vue application

Welcome to the community! I'm excited to ask my first question here on StackOverflow. I am currently working with vue.js-v2 and webpack. My goal is to ensure that data remains immutable for child components, which are loaded through the vue-router. T ...

Leveraging Webpack for the exclusive creation of a vendor bundle

Presently, our AngularJS project relies on Bower for front-end dependencies and the bower-concat Grunt task to merge bower_components into a single libraries.js file. Similarly, we assemble library CSS files into a libraries.css. Looking ahead, we aim to ...

What is the best approach to conceal elements from the main template in Meteor using a template event?

I have a main template along with two others that are displayed using Iron routing: <template name="main"> <div id="templateMain" name="templateMain"> <a href="nfnoscar">The Legend of NFN Oscar</a> <br/> <a h ...

A guide to implementing VantaJS in SvelteKit

Can someone guide me on incorporating Vanta JS from a SvelteKit project? I've attempted to add it in +page.svelte, <script lang="ts"> import VANTA from "vanta"; import * as THREE from 'three'; VANTA. ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

The node.js tutorial hit a snag due to the absence of the bson module

A Little Background I'm currently working on following a tutorial that can be found here. This tutorial involves setting up a restful web app using Node, Express, and MongoDB. My MongoDB database is up and running on another Linux machine, and I kno ...

JavaScript code for invoking the phone pluginInstructions for utilizing the phone plugin

Trying to implement a phone gap plugin with two parts using cordova 2.0.0 and eclipse. The java part is as follows: package org.apache.cordova; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.cor ...

creating an identical copy of a dynamic element's size

I am currently working on a project using react js where I need to incorporate multiple images. My goal is to have standard background divs / rectangles that match the exact size of each image, allowing for animations to be performed on top of them. The sn ...

Conceal an <article> element if its src attribute is blank using jQuery

Is there a way to hide articles with empty images? <article data-stars="<?php echo $StarRating[6];?>" name="<?php echo $Price[6];?>" class="box"> <img width="270" height="160" alt="" src="<?php echo $img[6][1];?>"></a> ...

How can I programmatically refresh a recursive ng-include in AngularJS?

Using a recursive script within my Angular application, I am displaying a visualization of multiple objects. However, whenever I modify the structure of an object dynamically, the view does not automatically update. It appears that the ng-include directiv ...

Using an XMLHttpRequest to obtain a response from a servlet

Running a jetty server to respond to GET requests has been successful so far. When accessing the request through a browser using localhost:8080/sp or 127.0.0.1:8080/sp, the correct data is returned. public void doGet(HttpServletRequest request, HttpServle ...

Redux dealing with collections of objects and searching through deeply nested objects

Being new to React and Redux, I am seeking a cleaner and more efficient way to structure my state. Currently, my state is organized as follows: --Character ---id ---name ---race ----id ----raceName ----traits -----trait ------id ------name ------descriptio ...

Creating a like button using AJAX in Django

Is there a way to implement a like button in Django using ajax without the need for a page reload? I've tried setting up my HTML and Ajax function, but it's not working properly. <form method="POST" action="{% url 'video: ...

What is causing the breakdown in communication between my server and client?

While utilizing React and an Express server for the backend, I am facing an issue where my API call to server.js is not going through. The React client is running on port 3001 and the server on port 3002. The fetch code in CreateAccount.js is as follows: ...

Managing conditional parameters with Typescript

I am currently in the process of creating a custom wrapper component for Material UI's TreeView. In this wrapper, I aim to replicate certain functionalities by allowing the passing of props to the TreeView component. One specific prop I am focusing on ...

Discover the magic of v-model in Vue 3 Composition API

Can someone help with managing reactivity in form fields using Vue3 Composition API? I'm having trouble getting my code to work correctly. When I type text into the input field, Vue devtools does not show any changes in the ref data. Here's a sim ...

Combine a specific number of elements in an array using JavaScript's comma-separated join without relying on jQuery

In my current project utilizing Vue and Quasar, I am hesitant to incorporate jQuery. Any suggestions on how to achieve a comma-separated string from an Array without using a loop? Ideally, I want to only combine a specific number of elements together. ...

Using a modal within a map function: Tips and tricks

I've been working on a Gallery application using React.JS and Reactstrap. The application uses the map() function to display each piece of art in a Card. Each card has a button that triggers a modal to show more data from the map function. However, I& ...

Is there a way to update the value of an element that is continuously changing through a setInterval() function when hovering the mouse over it?

I am currently a novice working on developing a pomodoro timer. At the moment, when you click the button to start the timer, it switches to displaying the remaining time once activated. One of the features I want to implement is the ability for users to h ...