简体   繁体   中英

Javascript Shallow copy of an object is undefined?

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.

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 (ie this.root = new Node(0,0,width,height); ) and then access it with this.root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM