Why is it not possible to pass references when utilizing a self-invoking function?

I have been experimenting with the IIFE pattern for some of my modules lately and encountered a problem that has stumped me. In my current project, I need to pass a few global variables for usage. One of these is the global googletag variable which initially loads with a default state but changes once external code is loaded.

However, I noticed that it doesn't update because the pattern creates a copy instead of a reference. To simplify the issue, consider the example below.

window.globalLevel = 'First';

var Module = (function(_g){
  function _stuff(){
    return _g;
  }
  return {
      get stuff(){
        return _stuff();
    }
  }
})(window.globalLevel);

// Initial state.
console.log("In Module:", Module.stuff);   // "First"
console.log("In Top:", window.globalLevel) // "First"

// After change.
console.log("--- Changing value ---")
window.globalLevel = 'Second'
console.log("In Module:", Module.stuff);    // "First"
console.log("In Top:", window.globalLevel)  // "Second"

Is there a way to resolve this? What adjustments or considerations should be made? Should I simply refer directly to window.globalReference in the module? It may seem messy, but it seems to work.

JS Fiddle

Answer №1

Your _data currently gives back the initially passed argument, which is _g. Therefore, even if you change the global variable using window.globalData = 'Second', the argument remains unchanged, resulting in the original argument being echoed back. To resolve this, you should return window.globalData:

window.globalData = 'First';

var Module = (function(){
  function _data(){
    return window.globalData;
  }
  return {
      get data(){
        return _data();
      }
  }
})(window.globalData);

// Initial state.
console.log("In Module:", Module.data);   // "First"
console.log("In Top:", window.globalData) // "First"

// After change.
console.log("--- Changing value ---")
window.globalData = 'Second'
console.log("In Module:", Module.data);    // "First"
console.log("In Top:", window.globalData)  // "Second"

If window.globalData were an object instead of a primitive, both the global variable and the argument would point to the same object in memory. In such a case, your _g function would work as intended:

window.globalData = { value: 'First' };

var Module = (function(_g){
  function _data(){
    return _g.value;
  }
  return {
      get data(){
        return _data();
      }
  }
})(window.globalData);

// Initial state.
console.log("In Module:", Module.data);   // "First"
console.log("In Top:", window.globalData.value) // "First"

// After change.
console.log("--- Changing value ---")
window.globalData.value = 'Second'
console.log("In Module:", Module.data);    // "First"
console.log("In Top:", window.globalData.value)  // "Second"

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 button's status changes to disabled until I click outside the input field in Angular

I am currently facing an issue with a form (heat index calculator) that requires 2 inputs - a dropdown and a button. The button is disabled when there are no inputs or if the inputs are invalid. Everything works correctly, except for the fact that even whe ...

Pausing for the completion of AJAX calls within a $.each loop before proceeding with the function execution

I am looking to trigger a function only once all of the AJAX calls within my $.each loop have finished executing. What is the most effective approach to accomplish this task? function recalculateSeatingChartSeatIds() { var table_id = $(".seatingChar ...

Encountering incorrect JSON formatting even though the content is accurate

I'm encountering an error while trying to fetch the JSON. It seems to be in the wrong format. Below is the JSON data: { "favorite_page_response": "<div class=\"col-md-12 col-lg-12\">\n <div class=\"cart\ ...

The initial number is inserted within the text box upon entering the final number

Whenever I enter the final digit, the text-box swallows up the initial number (it vanishes), resulting in an additional space. https://i.stack.imgur.com/Vfm8s.png https://i.stack.imgur.com/od4bQ.png Upon clicking outside of the text-box, the formatting ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

Is there a method to update the res object following a couchbase DB call without encountering the error "Error: Can't set headers after they are sent"?

let express = require('express'); let searchRoute = express.Router(); searchRoute.get('/', function(req, res, next) { console.log('1'); databaseCall(function(error, result) { if (error) { res.sta ...

Creating a dynamic form field using JavaScript

I'm struggling with a JavaScript issue that requires some assistance. I have a form sending an exact number of inputs to be filled to a PHP file, and now I want to create a preview using jQuery or JavaScript. The challenge lies in dynamically capturin ...

An issue has occurred: TransformError SyntaxError: Unexpected keyword 'const' was encountered

While practicing programming with React-Native, I encountered a problem that I couldn't figure out how to solve. I attempted to use solutions from various forums, but none of them worked. import { StyleSheet, Text, View, Image } from 'react-nativ ...

Having trouble with your browser freezing up after an AJAX request finishes?

Going through a tough time trying to figure this out for the past two days, but still struggling without any clue. Here's what I've been up to: Firstly, I upload a file using AJAX and instantly start processing it on the backend. $.ajax({ t ...

Mapping Longitude and Latitude with TopoJSON and D3

Currently utilizing the UK Geo JSON found at this link to generate a UK SVG Map. The goal is to plot longitude and latitude points onto this map. The GeometryCollection place is being added to the map in the following manner: data.objects.places = { ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

Mastering sorting in AngularJS: ascending or descending, the choice is yours!

I have set up a table view with infinite scroll functionality. The table contains 2000 objects, but only shows 25 at a time. As the user scrolls to the bottom, it loads an additional 25 elements and so on. There is a "V" or "^" button in the header that sh ...

Utilizing the power of async/await to simplify Hapi17 route abstraction

Trying to understand the transition to async/await in Hapi 17 is a bit of a challenge for me. My main focus is figuring out how to modify an abstracted route to make it compatible with async/await. Here is a snippet from my routes\dogs.js file: con ...

Submitting Multi-part forms using JQuery/Ajax and Spring Rest API

Recently, I started exploring JQuery and decided to experiment with asynchronous multipart form uploading. The form includes various data fields along with a file type. On the server side (using Spring), I have set up the code as follows: @RequestMapping ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

Connects URLs to the displayed outcomes in jQuery Auto-suggest Interface

This particular code snippet has been modified from a tutorial on jQuery autocomplete <!doctype html> <html lang="en> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...