Can you explain me why this object does not understand ‘this’?
var circle = {
radius : 20,
x : 100 - this.radius / 2,
y : 100 - this.radius / 2,
}
console.log(circle.x) // returns NaN, why?
because that’s not how
thisworks in JS.thiswill only be a reference to your object when you somehow cause your object to be assigned as thethisvalue of a function’s calling context.you can’t reference an object literal from itself while it is being created, because it doesn’t yet exist.
If you’re creating circles, you might consider using a constructor:
Because you’re invoking
Circleas a constructor usingnew,thisinside the constructor invocation will be a reference to the object being created. That object is implicitly returned since you’re not explicitly returning some other object.