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 this
works in JS. this
will only be a reference to your object when you somehow cause your object to be assigned as the this
value 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:
function Circle(radius) {
this.radius = radius,
this.x = 100 - this.radius / 2,
this.y = 100 - this.radius / 2,
}
var circle_20 = new Circle( 20 );
Because you're invoking Circle
as a constructor using new
, this
inside 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.
Here is a simple illustration:
//Saul was born: Initialize the parent!
var parent = {
youngestChild: 'Small Saul'
};
//Tim was born: Overwrite the parent!
parent = {
youngestChild: 'Tiny Tim',
currentYoungestChild: parent.youngestChild
};
alert(parent.currentYoungestChild);
Who is parent.currentYoungestChild
?
Like many developers, I thought parent.youngestChild
would be set to 'Tiny Tim'
before it would be set to parent.child
. If that were the case, it would be set to 'Tiny Tim'
.
However, it turns out that all children are evaluated prior to being stored on their parent, so
parent.currentYoungestChild == 'Small Saul'
Here's a fiddle if you want to try it out.
One explanation for this functionality is because then order of child declarations do not matter. For example, the following would have had a different outcome if objects were evaluated and stored sequentially:
parent = {
currentYoungestChild: parent.youngestChild,
youngestChild: 'Tiny Tim'
};
Long story short: Initializing child elements from other child elements in an object declaration will not work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With