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

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Aurelia: Understanding the Integration of a View/ViewModel from an npm Package

We've decided to implement Aurelia for the frontend of our application. With multiple projects in the pipeline, we are looking to streamline the process by packaging our custom code into npm packages that can be easily integrated by developers. This w ...

Changes to a key value are not reflected in the array of objects

When making changes to input fields within an array of records that include Date and Text fields in a table, the data is not updating as expected. I am encountering issues where changing the Date input results in undefined Text values, and vice versa. My g ...

Creating a visually appealing gantt chart in React Native using the react-google-charts library - here's how!

These are the current packages I am using: react-google-charts 1.5.5 react 16.0.0-beta.5 react-native https://github.com/expo/react-native/archive/sdk-22.0.1.tar.gz I am currently working on rendering a Gantt Chart and you can find an example here and a ...

I'm looking for guidance on effectively utilizing filter and map within the reducers directory to manipulate the workouts objects

I am encountering an issue while trying to send delete and update requests for the workout object. The error message indicates that the filter function is not compatible as it's being applied to an object instead of an array. Here is the snippet of co ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

Is there a possibility of encountering an endless update loop within a component's render function?

Hello! I am a beginner in Vue.js and I have encountered an issue with my function. Instead of increasing my variable to 1 as expected, it is increasing it to a random number every time. The console is displaying the following error message: "You may hav ...

Just released a new npm package called vue-izitheme. It's fully functional from the command line, but for some reason it's not showing up in search results. Any suggestions on how to fix

I released my project, vue-izitheme, two days ago but I can't seem to find it when searching. It is functioning correctly from the command line and has already been downloaded 44 times. Do you have any thoughts on what could be causing this issue? ...

How can I use D3.js to form a circular group in an organization structure, link it with a circular image, and connect

Is it possible to create a radial grouped circle using d3.js, similar to the image below: I have written some code as shown below. However, I am facing challenges in connecting every circle with a curved line and displaying a tooltip when hovering over a ...

Having trouble with CSS transitions in a Next.js or Tailwind application?

"use client"; import React, { useState } from "react"; import Image from "next/image"; import Link from "next/link"; const NavigationBar = () => ( <div id="navbar"> <Link href="/">Home</Link> <Link href="/about">About& ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

Is it possible for an AJAX request to return both HTML data and execute callback functions simultaneously?

Is it possible to update the content of an HTML div and call a JavaScript function with specific parameters obtained through AJAX after the completion of the AJAX request, all within a single AJAX call? ...

Leveraging webpack for requiring modules in the browser

I've been attempting to utilize require('modules') in the browser with webpack for the past couple of days, but I could achieve the same functionality with browserify in just 5 minutes... Below is my custom webpack.config.js file: var webp ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

Managing cookies in PHP and JavaScript can present challenges due to variations in how different browsers

Our website utilizes ExpressionEngine as the CMS and Magento's cart for e-commerce. I am encountering challenges with cookies and their accessibility in various sections. A cookie is used for storing search selections, allowing users to return to our ...

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

Error [ERR_MODULE_NOT_FOUND]: Module could not be located in vscode

Issue with VS Code: Module Not Found Error View the image associated with the erroreN.png ...

Transformation from a class component to a function component in React JS

I have a class component that I need to convert into a functional component. So, I started by refactoring the constructor. Below is the original class component: class EventCalendar extends React.Component { constructor(props) { super(props) ...