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

What is the best way to translate this code into JQuery ajax?

I have some code here that is currently using Javascript AJAX. I'm interested in converting it into jQuery AJAX, can someone help me with this? var mine = new XMLHttpRequest(); mine.onreadystatechange = function() { if (mine.readyState == 4 &am ...

What is the best way to transform a JavaScript object into a JavaScript literal?

Currently, in my nodejs project, I have an object defined as follows: const objA = { key : 'value' }; My goal is to create a new file named obja.js which should contain the same literals from the object, rather than as a JSON literal. How can I ...

Class for making elements draggable using jQuery UI

Is it possible to use jQueryui's draggable/droppable combo and add a class to the dragged item when dropped into a specific container, rather than adding a class to the container itself? I've tried adding a class to the container, but that is not ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

How to use jQuery to iterate over changing elements and retrieve their data values

Exploring the potential of a collapsible panel to meet my requirements $(".sport").on("click", function() { var thisId = $(this).attr("id"); var thisChildren = $(this) + ".sportlist"; $(thisChildren).each(function(index) { }); }); <link ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggested to t ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

Retrieve the attribute values of an element in Angular after utilizing a template

As a newcomer to Angular, I am exploring the use of custom directives for the first time. Currently, I have a table where each cell contains a data attribute such as "data-dept="service". Before applying a directive to overwrite this value, I would like to ...

Ways to create interactive multiple dropdown menu using vue-multiselect

I'm not sure if it's possible to achieve what I want with Vue for a specific component by changing its data and automatically loading it. Below is my expectation (tried in jQuery) var data = {country:{type:'dropdown',values:[' ...

What steps should be taken to retrieve the contents of a file that has been chosen using the browse

You have successfully implemented a browse button that allows the user to navigate the directory and choose a file. The path and file name are then displayed in the text element of the Browse button complex. Now, the question arises - how can I extract dat ...

Creating an HTML Canvas using an AngularJS template

I am facing an issue with rendering html elements on a canvas using html2canvas JS. I am utilizing AngularJS for data binding on the html page, but unfortunately, the dynamic data is not showing up on the canvas generated from these html elements. For inst ...

Using Node.js to invoke an identifier loop

Having some trouble with this loop. Should I include variable c in the loop as well? Let me provide some context: there is a table and child(i) changes for every row. The SelectorT receives a sentence structured like this: Now\nIs\n09:00\n4 ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Error: JSX elements that are next to each other must be contained within a parent tag

I am trying to display articles on a page using ReactJS, but I encountered an issue where I need to wrap enclosing tags. It seems like React doesn't accept identical tags next to each other. How can I effectively show tabular data? render() { r ...

Implementing color transitions in javascript

Everyone talks about transitioning things in CSS, but have you ever thought about transitioning background colors in JavaScript? I'm currently working on a function that changes the background color of a div with the id of ex1 to green. However, I&apo ...

Modify the Text Displayed in Static Date and Time Picker Material-UI

Looking to update the title text on the StaticDateTimePicker component? Check out this image for guidance. In the DOM, you'll find it as shown in this image. Referring to the API documentation, I learned that I need to work with components: Toolbar ...

What is the best method for incorporating a YouTube embedded video into an image carousel using HTML and CSS?

I'm encountering an issue with my product carousel that includes an image and a video. The image displays correctly, but when I attempt to click on the video to have it appear in the main carousel view, it doesn't function as expected. Here is a ...