Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of the one created by the constructor itself. The JavaScript snippet provided below illustrates this problem.

While I understand that conventional javascript would behave differently, I'm curious as to why Vue JS is interpreting the code in such a manner.

function node (){
  this.x = Math.random();
  this.y = Math.random();
}

let nodes = [];
nodes.push(new node());
console.log(nodes); 

JS Fiddle: https://jsfiddle.net/ex080/t690v9pu/

HTML:

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <button @click="generate">Generate Object</button>
  <li v-for="node in nodes">
    {{node.num}}
  </li>
</div>

JavaScript:

new Vue({
  el: '#app',
  data: {
    nodes: []
  },
  methods: {
    node() {
        num = Math.random();
        console.log(num);
      },
      generate() {
        this.nodes.push(new this.node());
      }
  }
});

Answer №1

You have not saved a reference to the variable num anywhere. One way to do this is by returning an object from the node method:

 return {num:  Math.random()}

Additionally, using new creates an object and sets a context as shown below:

function node (){
  // 'this' refers to the instance of the node object
  // it maintains references to the properties x and y
  this.x = Math.random();
  this.y = Math.random();
}

On the other hand, declaring the function node() just defines a function without constructing an object.

node() {
    // 'num' is declared and only accessible within the function's scope
    // it may be eligible for garbage collection once the function finishes execution.
    num = Math.random();
    console.log(num);
},

The approach I presented with returning the object achieves similar outcomes to using new node() like in your initial example.

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

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

Challenges I'm Facing with my Vue.js API Integration using axios

I am currently working on a bookstore application using Vue.js. The book data is stored in this API . However, I am encountering issues displaying the information on my HTML page with the provided function and I am struggling to identify the root cause: ...

What is the best approach to send a value to the controller?

How can I pass a value to the child controller using the stateProvider in Angular? This is what I have so far: $stateProvider .state('test', { url: '/test', views: { '': { ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Broadcast a public message with the sender specified using Socket.io

As I dive into using socket.io, I've managed to send private messages successfully. However, I'm now curious about how to send a message to all users at once. In the code snippet below (used for testing purposes), the first user receives a privat ...

Latest News: The store is now received in the mutation, instead of the state

An update has been made to this post, please refer to the first answer After thorough research, I couldn't find a solution to my issue despite checking several threads. This is my first time using the Quasar framework and it seems like I might have o ...

"Permission denied to access restricted URI" error encountered while attempting to utilize ng-template functionality

I am attempting to implement ng-include for recursive templates in my HTML. After testing it on jsfiddle and confirming that it works, I tried the same locally. However, I encountered the following error: Error: Access to restricted URI denied createHttpB ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

Scrolling with jQuery to create a fixed navigation bar

I'm having an issue with my navbar on my website. I used CSS and jQuery to keep it fixed at the top, but now when I click on a menu item, it doesn't scroll to that section of the page. Can anyone help me troubleshoot this problem? ...

Adding a custom property to a React component

Currently, I am facing an issue while attempting to modify an MUI component. Everything works smoothly until I execute the build command, at which point it fails. I have experimented with a few variations of this, but essentially I am looking to introduce ...

Toggle the visibility of a hidden div by clicking a button

After spending several days working on this project, just when I thought it was perfect, I had to completely restructure the entire page. Now I'm feeling stuck and in need of some help. The issue is that I have three images with buttons underneath eac ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

Upgrade the jQuery code from version 1.4.2 min to version 1.10.2 min

Hey there, I'm looking for assistance with updating the code below to use jQuery 1.10.2. The backslashes are present because I am using it with PHP and need to escape special characters. I'm not very familiar with JavaScript and unsure of the ch ...

Retrieving information from a separate JavaScript file

I'm currently developing a Discord Bot and my code is all contained within one file. My goal now is to break this code up into multiple files for better organization. For instance, I plan to have: index.js which will handle all the requires (e.g. var ...

During the build process in Vue.js, you can pass an argument through the command line that will be utilized by an .env.[mode] file

Objective: I am looking to pass an argument during build time in order to use it in my .env.production file or as an environment variable if necessary. .env.production file: VUE_APP_CLIENT_ID=00-should-be-using-what-was-passed-by-command-00 Docker fil ...

Creating nested directories in Node.js

I am attempting to accomplish the following task Create a function (in any programming language) that takes one parameter (depth) to generate folders and files as described below: At depth 0, create a folder named 0, and inside it, create a file with its ...

Execute an AJAX request in JavaScript without using string concatenation

On my webpage, users input code in a programming language which can be over 2000 characters long and include any characters. When they press the send button, the code is sent to a server-side script file using JavaScript AJAX. Currently, I am using the fo ...

Navigate to a precise point in a video using react hooks in videojs

I am currently working on adding a feature that allows users to skip forward or backward by 15 seconds in a video. However, I am encountering difficulties when it comes to updating and setting the current time accordingly. const videoNode = useRef(null); ...

`Incompatibility with Internet Explorer causes AJAX loader GIF to fail when using asynchronous POST requests`

Is there a way to display an AJAX loader gif during an asynchronous POST request on Internet Explorer? It seems that the request process stalls and the updated content is not visible when using Internet Explorer. However, everything works fine on browser ...