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