Skip to content
Advertisement

Incomprehensible object reassignment in javascript

I’ve been looking at the examples of this game engine and I really don’t understand why it reassigns the object, I code in java and I’m learning javascript, it may be a concept error.

example https://blacksmith2d.io/Docs/Examples/Arcade-Physics/CollisionEvents

onassetsLoaded() event he is setting object properties and then reassign it again below.

this.arcade = arcade;
this.circle = circle;
this.box = box;

also i don’t understand this part on if statement

!this.circle 

Advertisement

Answer

About these statements:

this.arcade = arcade;
this.circle = circle;
this.box = box;

Earlier in that block of code, all variables that occur at the right side were defined as local variables (local to the method onAssetsLoaded):

const arcade = ...
const circle = ...
const box = ...

So the assignments that have you wondering are in fact copying references from local variables to instance variables (i.e. properties). This is needed to not lose this information once the onAssetsLoaded call has completed.

As to this expression:

!this.circle 

The not-operator (!) can be used on any expression. It evaluates to true when the operand is “falsy”. In JavaScript values like undefined, null, 0, "", NaN, are considered “falsy”, while all objects are considered “truthy”. Here it is used to detect that this.circle has not been assigned a proper value, i.e. it would mean that onAssetsLoaded had not yet been called, and this.circle was still undefined.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement