Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referring to an javascript object proprty (using this) while creating it

Tags:

javascript

oop

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?
like image 407
Asaf Katz Avatar asked Dec 21 '22 09:12

Asaf Katz


2 Answers

  1. 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.

  2. 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.

like image 80
user113716 Avatar answered Dec 24 '22 01:12

user113716


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!

like image 22
Briguy37 Avatar answered Dec 24 '22 03:12

Briguy37