+ 6

Hello. I was making a code and I just found this error which really bugs me.

I am trying to make a code, and I made an array of objects with different properties. It is something like: [{x:W, y: 200, h: this.y-100}] and etc. The issue I have is that h is evaluated to NaN because this.y is undefined. Why is that? How could I define the property h being property y - 100? I always avoided this, but I do not know what is the problem. I would appreciate some help.

17th Sep 2017, 2:24 PM
Gami
Gami - avatar
4 Antworten
+ 4
You cannot do that with an object litteral assignement: the object properties are only accessible once the object is created (ie: after you close the curly braket)... The solution is to assign your object values in two times, or create a JS class-like function (an object constructor): var my_litteral_obj = {x:W, y:200}; my_litteral_obj.h = my_litteral_obj.y-100; ... or: function MyClassObj(_x,_y) { this.x = _x; this.y = _y; this.h = this.y-100; } var my_class_obj = new MyClassObj(W,200); In the first case, there's no related 'this' object, while in second case, the constructor is called with the 'new' keyword, so 'this' is initialized to a new empty object reference... and is already accessible in the constructor scope ;) In a certain point of view, it's near to do: var my_obj = {}; // create an empty object my_obj.prop = 42; my_obj.value = my_obj.prop; ... but from inside the object itself, with help of the special object 'this' :P
17th Sep 2017, 3:01 PM
visph
visph - avatar
+ 8
Thank you guys. I will use the constructor function then :)
17th Sep 2017, 7:56 PM
Gami
Gami - avatar
+ 1
Try to use constructor function var obj = [new function() { this.W=1; this.x = this.W; this.y = 200; this.h = this.y-100; }]; console.log(obj[0].x); console.log(obj[0].y); console.log(obj[0].h); https://code.sololearn.com/W7MXx7FeT2t7/?ref=app
17th Sep 2017, 3:12 PM
Calviղ
Calviղ - avatar
0
I am not a profisional but try to creat h in new array after craeting y
17th Sep 2017, 2:51 PM
Akram Adil