So I am new to object definition in Javascript, and am trying to write a program that revolves objects as a practice. My problem is that when I am trying to define the object, some of the object properties are dependent on other parts of the object. I am not sure if this is even permitted, because in all my searching I have not been able to find any examples of it.
My question is basically this: can I use previously defined properties of an object to define that object. The most basic example of this would be something like this:
var alfred = {
dogs: 1,
cats:this.dogs+1,
}
Is this permitted? if so is this the right syntax? The reason I need to use a “this.” is because I am pushing newly created objects to a array of objects.The code of mine that is not working is below:
obj.push({
canvas:document.getElementById(canvasName),
canvasName:"canvas"+objNum,
image: img,
width:objWidth,
height:objHeight,
centerX:posX,
centerY:posY,
speed:speeds,
hypSquare:Math.sqrt((this.width*this.width)+(this.height*this.height)),
angleInSquare:Math.atan(this.height/this.width),
angle:startAngle,
angleTotal:this.angle+this.angleInSquare,
offX:(this.hypSquare* Math.cos(this.anglesTotal))/2,
offY:(this.hypSquare* Math.sin(this.anglesTotal))/2,
centeredX:this.centerX-this.offX,
centeredY:this.centerY-this.offY,
})
when I call a
console.log(obj[objNum].hypSquare);
(where objNum is just the index of the object in the array) I will get NaN even though if I call
console.log(obj[objNum].width);
I will get the value of objWidth. Is there just a syntactical issue, or is my understanding of objects fundamentally flawed…
Thank you in advance for your time!
Isaac
No, you can’t do that. You have to close the object initializer and then add the other property, e.g.:
So for your
obj.pushcall, you’ll have to use a temporary variable (likealfredabove), you can’t just use an inline object initializer.