The ability to retrieve variables within a certain scope from a function that is declared externally

Is there a method to access and print the value of a closure variable, temp, from a function defined outside the closure but referenced within it without passing temp as an argument to the function?

var funcA, funcB;

funcA = function () {
   console.log(temp);
}

funcB = function () {var temp, funcC;
  temp = 1;
  funcC = funcA;
  funcC();
}
funcB();  // temp is undefined.

This solution works only when funcA is defined inside funcB:

funcB = function () {var temp, funcA, funcC;
  temp = 1;
  funcA = function () {
       console.log(temp);
  }
  funcC = funcA;
  funcC();
}
funcB(); // 1

I am attempting to simplify some complicated code by moving certain function definitions out of outer functions. Is there a way to define funcA externally to funcB but still reference the temp variable without needing to pass parameters?

Although Javascript is said to have lexical scoping rather than dynamic runtime scoping, can referencing a function (such as funcA via funcC) in funcB provide access to scoped variables while meeting the requirements of lexical scope?

Answer №1

After reading Akinkunle Allen's insightful comment, I was able to devise a solution to my issue.

function customFunc () {
  var innerFuncA, innerFuncB, temporary;

  innerFuncA = function () {
     console.log(temporary);
  }

  innerFuncB = function () {var innerFuncC;
    temporary = 1;
    innerFuncC = innerFuncA;
    innerFuncC(); 
  }
  return innerFuncB();
}

customFunc(); // Output: 1

Answer №2

A mixture of both positive and negative.

The use of the keyword var to declare variables can vary depending on the current scope. When var is utilized in the global scope, it becomes optional as the variable transforms into a property of the global object, which is usually represented by window in browsers.

Hence, the following code snippets yield the same outcome when executed within the global context:

var temp = 1;
window.temp = 1;
this.temp = 1;

All three statements above essentially refer to window.temp due to the global setting.

If var is used inside a function, the variable is bound to that specific function's scope. Since functions are objects in Javascript, local var variables will persist as long as the parent function remains in use elsewhere.

Javascript traverses through executing scopes to locate a variable identifier, enabling inner functions to access their outer function's variables (as demonstrated in your example).

You have the opportunity to manipulate the this reference within functions.

In Javascript, the identifier this is dynamic and can be altered. This allows passing a variable to an external function declared outside the calling function. By using this.temp to reference the variable, function funcA effectively displays its value.

funcB = function(otherFunc)
{
    this.temp = 1;
    otherFunc();
}

funcA = function()
{
    alert(this.temp);
}

funcB(funcA);

Check out the jsfiddle example linked below for further illustration.

Modifying this dynamically presents various advantages, particularly in enabling a function to accept closure references executed with a custom this reference.

For instance, consider a click event handler where this denotes the DOM element triggering the event.

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

Tips for transferring information between routes in Node.js using Express.js

How can I add a specific attribute to the request object and access it from another route after redirection? Below is an example of what I am looking for: const express = require('express') const app = express() app.get('/test1',(req, ...

Can one sever the connection using the bittorrent protocol?

At this time, A and B are in the process of transferring files directly. My goal is to execute code that severs the connection between the torrent and B. I attempted to disconnect the ongoing connection with codes provided here which included the followi ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

When the button is clicked, send data using 'POST' method to the php file and fetch

<script> $(document).ready(function(){ $("#vE_rebtn").click(function{ var reverifyEmail = '<?php echo $_SESSION["verifyEmIPv"]; ?>'; $('#rE_rebtn').hide(); $('#re_ ...

Consecutive POST requests in Angular 4

Can you assist me with making sequential (synchronous) http POST calls that wait for the response from each call? generateDoc(project, Item, language, isDOCXFormat) : Observable<any> { return this.http.post(this.sessionStorageService.retriev ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

Conceal the legend in Highcharts using Python script with Django

Need some assistance with a Django and Highcharts.js project I'm working on. Objective: hide the legend in a Highcharts chart from my views.py script. In my views.py file, I've successfully plotted various charts but struggling to hide the lege ...

Enhance user experience by implementing an autocomplete feature for a text input field

Can you name the process in which a form is automatically filled using database information without needing to refresh the page? One common example of this technique is seen on platforms like Google or Facebook, where they predict friends you may be searc ...

Rotate the mat-select arrow when the dropdown opens (moving in both upward and downward directions)

Currently, I have a mat-select dropdown icon arrow that toggles facing up or down based on user clicks. However, after selecting an option and closing the dropdown, the arrow remains in the upward position unless further clicked and held. I have attempted ...

Implementing Asynchronous Rendering in React Router 4

I've been working with React Router 4 and trying to implement Redirect(Auth) following a guide. However, I'm facing an issue with rendering based on the promise returned by an AJAX call. It seems like my rendering logic inside the promise is not ...

Using an HTML element to pass a variable into a replace function

I am looking to highlight a 'SearchString' by replacing it with <span style="background-color: yellow">SearchString</span> within a targetString. The SearchString varies, so I am wondering how I can make this happen. This is what I ...

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

Unable to send headers to the client in expressjs as they have already been set

After successfully logging in, I am trying to redirect to another page but keep encountering the error message "Cannot set headers after they are sent to the client". I understand that I need to place the res.redirect method somewhere else in my code, bu ...

Ways to eliminate existing information when conducting a search

Recently, I was tasked with integrating a search engine into a website that already has a list of data displayed on the first page. The challenge I faced was figuring out how to hide or remove this existing data when a new search request is made. You can v ...

Utilizing on() in conjunction with a map function

Currently, I am in the process of refactoring my code and have decided to revisit how I handle on events by utilizing mapping. Below is a snippet of what I currently have: $('img#sorc').on({ mousemove: function (e) { alert('tes ...

Dealing with name conflicts in Typescript when using multiple interface inheritance

Is it possible to securely implement two interfaces in Typescript that both have a member of the same name? Can this be achieved? For example: interface IFace1 { name: string; } interface IFace2 { name: string; } class SomeClass implements IFace ...

Is it possible to communicate with a native chat application such as Pidgin using Node.js?

Is there a seamless way to connect with a native messaging client like Pidgin using Node.js? I attempted to develop a basic chat system utilizing the XMPP protocol in conjunction with Node.js (using https://github.com/astro/node-xmpp followed by https://g ...

Is it possible for you to pinpoint the mistake in the code below?

I've been trying to locate an error in the function but have been unable to do so. As a beginner in this area, I would appreciate your patience. <html> <head><title>print names</title> <script langua ...

What is the best way to prevent event bubbling in this particular code snippet?

$('#div1').on('click', '#otherDiv1', function(event){ //Show popup $('#popupDiv').bPopup({ modalClose: false, follow: [false, false], closeClass: 'close ...

Dynamic options can now be accessed and modified using newly computed getters and setters

When using Vuex with Vue components, handling static fields that are editable is easily done through computed properties: computed: { text: { get() { return ... }, set(value) { this.$store.commit... }, }, }, <input type ...