The process of assigning a function to an object in JavaScript is currently not functioning properly

After updating a Vue2 project to Vue3, I ran into an issue with Javascript. It seems that the language now prevents me from assigning a function to an object.

In the code below, I define a function "bar" within a loop. While I can successfully call the function within the loop as "bar(i)", and outside the loop as "ff('00')", I encounter an error when trying to assign the function to the api_calls object. This is puzzling to me and I'm not sure what mistake I might be making.

I also upgraded from node-v10.15.3-x64 to node-v18.16.0-x64.

export function generate_api_calls(app_name) {
  let api_calls = {}

  api_calls['cameraFeed'] = `http://${hostname}:${camera_port}${CAMERA_FEED_URL}`

  let ff
  let items = [1, 2, 3, 4]
  for (let i in items) {
    let name = items[i]
    function bar(j) {
      logger.info(`bar ${j}`)
    };

    bar(i)
    ff = bar
    api_calls[name] = bar;
    logger.info(`generate_api_calls api ${name} ${JSON.stringify(api_calls)}`)
    logger.info(`generate_api_calls api ${JSON.stringify(api_calls[name])}`)
  }
  ff('00');
 
  logger.info(`generate_api_calls 5 ${JSON.stringify(api_calls)}`)
  return api_calls
}

The output is:

2023-05-30_17:39:24.582-gui.vue.app-INFO: bar 0
2023-05-30_17:39:24.582-gui.vue.app-INFO: generate_api_calls api 1 {"cameraFeed":"http://localhost:5051/camera/feed"}
2023-05-30_17:39:24.583-gui.vue.app-INFO: generate_api_calls api undefined
2023-05-30_17:39:24.583-gui.vue.app-INFO: bar 1
2023-05-30_17:39:24.584-gui.vue.app-INFO: generate_api_calls api 2 {"cameraFeed":"http://localhost:5051/camera/feed"}
2023-05-30_17:39:24.584-gui.vue.app-INFO: generate_api_calls api undefined
2023-05-30_17:39:24.585-gui.vue.app-INFO: bar 2
2023-05-30_17:39:24.585-gui.vue.app-INFO: generate_api_calls api 3 {"cameraFeed":"http://localhost:5051/camera/feed"}
2023-05-30_17:39:24.586-gui.vue.app-INFO: generate_api_calls api undefined
2023-05-30_17:39:24.586-gui.vue.app-INFO: bar 3
2023-05-30_17:39:24.587-gui.vue.app-INFO: generate_api_calls api 4 {"cameraFeed":"http://localhost:5051/camera/feed"}
2023-05-30_17:39:24.587-gui.vue.app-INFO: generate_api_calls api undefined
2023-05-30_17:39:24.588-gui.vue.app-INFO: bar 00
2023-05-30_17:39:24.588-gui.vue.app-INFO: generate_api_calls 5 {"cameraFeed":"http://localhost:5051/camera/feed"}

Answer №1

Everything is functioning as expected. It's important to note that you cannot stringify functions using JSON.stringify. Please refer to the demo provided below.

const reporter = {
  log: console.log,
};

function create_data_calls(app_name) {
  let data_calls = {};

  data_calls['weather'] = 'fetchWeather';

  let ff;
  let items = [5, 6, 7, 8];
  for (let i in items) {
    let name = items[i];

    function baz(j) {
      reporter.log(`baz ${j}`);
    };

    baz(i);
    ff = baz;
    data_calls[name] = baz;
    console.log('check out the printed function --->', data_calls[name]);
    logger.info(`create_data_calls endpoint ${name} ${JSON.stringify(data_calls)}`)
    logger.info(`create_data_calls endpoint ${JSON.stringify(data_calls[name])}`)
  }
  ff('11');

  console.log('view the data_calls --->', data_calls);

  logger.info(`create_data_calls count ${JSON.stringify(data_calls)}`)
  return data_calls
}

create_data_calls('trial');

// observe how stringify doesn't include a function
console.log(JSON.stringify({
  result: 'xyz',
  func: () => {},
}));

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 is the best way to create an HTML form on-the-fly from a JSON object?

Could someone please assist me in understanding how to dynamically generate an HTML form based on a JSON object using JavaScript? ...

The meshes in my Unity game appear flipped after I import them from 3ds Max with skinning applied

After bringing my meshes from 3ds MAX to Unity with skinning, I've noticed that they appear inverted in-game. Both the mesh and normals seem to be reversed, giving them an eerie, ghost-like appearance. Interestingly, disabling the skin option resolv ...

Encountering an issue during the project build in Vue specifically related to ffmpeg.wasm

Hey there, I'm encountering the following error when trying to build the project using the $npm run build command https://i.stack.imgur.com/he8tb.png Currently, I am utilizing vuetify version "vuetify": "^2.4.0" since version 3.0 is still in beta. A ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

``There is an issue with the Nodejs required module variable not updating even after deleting

Feeling puzzled about the situation. Module 2 is supposed to require a variable from module 1, but even after deleting the cache, the variable in module 2 refuses to update when changes are made. Sample Module 1 var num = 6 function changeNum(){ num = ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

Include an option for whitespace characters when validating a file using regex

My text box has specific criteria for what is considered good or bad input. Examples of good input could include: GoodString GoodString88 99GoodString I want to avoid certain types of bad input, such as: Good*String Good&String However, I do want ...

Organizer featuring Outlook-inspired capabilities

My goal is to develop a system for efficiently managing appointments. Upon opening the application, I want to display a calendar control that will retrieve an individual's schedule from a SQL server database. For example, if the user has meetings sch ...

Performing an AJAX GET request to the API after a set time interval

The API is constantly updating with live values, so I am attempting to fetch the data every second and display it on the webpage. Although I used a GET request call every N seconds using set_interval(), the values only load once and do not update with eac ...

Forward ReactJS

https://i.stack.imgur.com/r0IAE.pngI'm having trouble implementing a redirect to a submit confirmation page after pressing the submit button on my form. The backend server is set up to send an email upon submission, but adding an href to the button pr ...

Is it possible to customize text or images using the window.location method?

Imagine I have a scenario with 3 unique servers as follows: https://server-1.com https://server-2.com https://server-3.com In my Vue application, I want to dynamically change an image based on the server being used. Can I achieve this by utilizing someth ...

What steps should I take to implement the features I want using Node.js?

My request is as follows: I need to pass an array of IDs to a function that will perform the following tasks: Check if a document exists in MongoDB. If it does, move on to the next ID. If not, create a document with the specified ID. If all the IDs ...

Is there a way to delay loading 'div' until a few seconds after the 'body' has been fully loaded?

Is there a way to delay the appearance of the "text-container" div after the image is displayed? I have attempted to achieve this using JavaScript with the following code: <script> window.onload = function(){ var timer = setTimeout("showText()",700 ...

Unable to perform navigation during page load in a React.js application

I attempted to navigate to a route that should redirect the user back to the homepage when postOperations isn't set in the localStorage. To save time, please review the code snippet focusing on the useEffect and the first component inside return(). im ...

Transferring JSON data using AJAX

I am having trouble sending JSON via AJAX using pure JavaScript. While I can successfully retrieve values back from PHP, I am struggling to retrieve a specific JSON array. var mname = ["john", "mary", "eva"]; var fname = 678; clicked_keyword_test = {"last ...

Execute PHP script after successful AJAX response

I've been struggling to find a solution for this issue. I have an Ajax function that continuously loops, waiting for a specific variable value. Once the variable is not equal to 0, I need to send the data to another script to update the database and t ...

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

Tips for interacting with the DOM in an Angular 4 application

I am trying to call the addItems method, but I keep getting an error: Uncaught TypeError: this.addItems is not a function Currently, I am using Angular 4 along with jQuery and the fullpage.js library. page-content.component.ts import { Component, OnI ...

Iview Table UI Cell

Is there a way to retrieve the cell data from a library iview table in Vue.js upon clicking? I am looking to capture both the value of the cell and the title of the column, and then modify the CSS of that particular cell. For instance, clicking on one ce ...

Ways to utilize a singular pathway in various situations?

In my Nuxt project, I have implemented an admin dashboard with a unique layout (sidebar) using <NuxtChild> to render child routes: Admin.vue <NuxtChild :key="$route.path" /> Simplified Routes: { path: "/admin", ...