Javascript Shallow copy of an object is undefined?

192 views Asked by At

I just started learning Javascript about a week ago so bear with me. I am attempting to make a basic physics engine using a quadtree and nodes as the backing structure for all objects. However in this snippet of code

102 Quadtree.prototype.insert= function(self, object){
103     if (object == null){
104         return;
105     }
106     var objectx,
107         objecty,
108         objectw,
109         objecth;
110     objectx = object.getDim()[0];
111     objecty = object.getDim()[1];
112     objectw = object.getDim()[2];
113     objecth = object.getDim()[3];
114     var cn = root;
115     if(cn == undefined){
116         console.log("asdgalkjh");
117     }

cn (current node) is returning undefined. Object is also null. I know that my problem is arising from not knowing how javascript objects work in detail. Could someone please give me a summary or point me where to read? Thanks.

here is my node and quadtree class for reference

94 function Quadtree(width,height){
95     this.width = width;
96     this.height = height;
97     this.MAX_LEVELS = 4;
98     this.MAX_OBJ = 2;
99     var root = new Node(0,0,width,height);
100     root.split();
101 }

13 function Node(x,y,width,height){
14     var x,
15         y,
16         width
17         height;
18     this.x = x;
19     this.y = y;
20     this.width = width;
21     this.height = height;
22     var hash = 0;
23     var objects = new Array();
24     var parent = null;
25     var child1 = null;
26     var child2 = null;
27     var child3 = null;
28     var child4 = null;
29 }

I realize I may be doing many things wrong, I come from a heavy java background and javascript objects are passed by 'call by reference' which is also confusing so far. Any help is much appreciated.

1

There are 1 answers

2
axelduch On

You are trying to access a private variable root which is accessible only in the QuadTree constructor.

If you want to use it anywhere else you will have to either make a getter or put it in public members (i.e. this.root = new Node(0,0,width,height);) and then access it with this.root