I want to create an object such that object.a is an array while object.b is the length of it and this is what I have:
var object = {
a:[1,2,3,2],
b: this.a.length
}
alert(b);
But this won’t alert 4. There is something wrong with b: this.a.length:
Uncaught TypeError: Cannot read property 'length' of undefined
I’d be glad if someone can explain to me why this is happening.
It would actaully alert 4 if I write it this way:
var object = {
a:[1,2,3,2]
}
alert(object.a.length);
[update] even create the object this way, it doesn’t work:
var object = {
a:[1,2,3,2],
b:object.a.length
}
The main problem is that in javascript data declaration like your first example, the value of
thisis not set to the object being defined. So sincethisis not your object,this.ainside the object declaration does not refer to theaproperty of your object.It is whatever it was in the context right before your data declaration. If that was the global context, then
thiswould be thewindowobject andthis.aprobably doesn’t exist. If it doesn’t exist (e.g. it’sundefined), then when you try to referencethis.a.length, you are trying to read the property.lengthoff something isn’t an object and that is a javscript error.As for solving this problem it is generally a bad idea to copy the length of an array to another property. That just gives you a chance for it to be wrong and out-of-sync with the actual length of the array. If you want the length of the array, you should just retrieve it upon demand with:
If you really want it to be a property (that has a fixed value and doesn’t change when
achanges), you can set it after you create the object: