0

I am learning Vue JS and ran into a particular issue while trying to populate an array with objects using a constructor function and the push function. In Vue JS, the push method adds a blank object into the array instead of the one created by the constructor. JS fiddle below.

I know in conventional javascript the code below would work fine, can anyone explain why Vue JS is interpreting the same code differently.

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());
      }
  }
});

1 Answer 1

1

You are not storing a reference to num anywhere. Try returning an object from the node method:

 return {num:  Math.random()}

Edit:

Using new creates an object and with it a context:

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

Declaring the method node() however is a function and not constructing an object.

node() {
    // 'num' is declared and is accessible only within the scope of the function
    // it is a candidate for garbage collection as soon as the function completes.
    num = Math.random();
    console.log(num);
},

The way I showed you returning the object, for the sake of demonstration, achieves the same as using new node() from your first example.

Sign up to request clarification or add additional context in comments.

3 Comments

that seems to work, but can you explain why the constructor function works in traditional javascript without the return and why exactly I need it in the Vue JS version?
Updated my answer hopefully that helps explain the differences
This could have been avoid if you would have added the 'use strict' mode to your java-script file. its one of the good practice which saves a lot of time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.