Someone
Someone

Reputation: 121

Constructors and Subproperties in Javascript

I have the following:

function Vector(X,Y,Direction)
{
    this.X = X,
    this.Y = Y,
    this.Direction = Direction
}

function Particle(Position,Size)
{
    this.Position = Position,
    this.Size = Size,
    this.Velocity = new Vector(0,0,0)
}

Vector is a constructor function which creates a vector object, this object is created by another constructor function, Particle, which creates a particle object under the Velocity property.

Will JavaScript parent the constructed Vector object's properties under the Particle object, or under Particle.Velocity? To cut it short, will new Particle() create this:

Particle.X

Or preferably this:

Particle.Velocity.X

This question may be phrased poorly, sorry. I simply have a hard time understanding the scope of the 'this' keyword in JavaScript.

Upvotes: 0

Views: 67

Answers (1)

slebetman
slebetman

Reputation: 113896

It will be Particle.Velocity.X. Not specifically because of the scope of this but because you did this:

this.Velocity = new Vector(0,0,0);

You're assigning to the Velocity property of the Particle object.

But this works differently in javascript so it's worth spending some time understanding it. It's not bound directly to the object where it's declared/written but rather bound at run time to different things depending on how the function/method is called.

For example, consider the following:

var foo = {};
foo.name = 'Frank';
foo.say = function () {alert('My name is' + this.name)}
foo.say();

as you would expect, the code above alerts "My name is Frank". But, if you do this:

var bar = {};
bar.name = 'Benny';
bar.say = foo.say;
bar.say();

the code above will alert "My name is Benny". That's because this is bound to the last word/name before the dot. So even if the function was originally declared in the context of foo, once it's called with bar as it's container object the this inside it will refer to bar.

For a complete description of how this works in javascript see my answer to this other question: How does the "this" keyword in Javascript act within an object literal?

Upvotes: 2

Related Questions