Introduction to Objects in JavaScript
Objects in JavaScript are a fundamental data type. They are collections of key-value pairs, where each key is a string and each value can be any data type. Objects are used to store, manipulate, and send data.
- Properties and methods
- How to access properties and methods
- Overview of this.state as an example of an Object
Properties and methods
-
Properties: These are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted.
-
Methods: These are actions that can be performed on objects. A method is a property that contains a function definition.
For example, consider an object representing a person:
let person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
In this example, firstName, lastName, and age are properties, while fullName is a method.
How to access properties and methods
Properties and methods of an object can be accessed using dot notation or bracket notation.
Dot notation
// Property
objectName.propertyName
// Method
objectName.methodName()
Bracket notation
// Property
objectName["propertyName"]
// Method
objectName["methodName"]()
Example using person object
// To access the firstName property of the person object
// Dot Notation Property
person.firstName
// Bracket Notation Property
person["firstName"]
// Dot Notation Method
person.fullName()
// Bracket Notation Method
person["fullName"]()
Object Summary
Understanding objects is crucial for understanding JavaScript, and they are used extensively in all the code we will be looking at.
Overview of this.state as an example of an Object
The “this.state” data structure is used to hold the state of the player and the environment in which the player is interacting. It has properties for the player’s current animation, the object the player is currently colliding with, the list of all objects the player has collided with, the direction the player is facing, the directions in which the player can move, and whether the player is dying.
Review the class PlayerBase and the test code that creates a “player” object.
var player = new PlayerBase();
In the test code, references to player.state
access the instance data this.state
via the player
object. Notice the dot notation that allows you to reference a key and assign a value. The dot notation and access patterns for key/value pairs are similar to Python dictionaries and Java hashmaps.
Note the mixture of data types used.
player.state.collision = 'wall'; // string type
player.state.collisions.push(player.state.collision); // array type
player.state.movement = {up: false, down: false, left: true, right: false, falling: false}; // object type
Review the PlayerBase and test code below and then do a deeper review of the completed code in the PlayerBase.js file.
%%js
class PlayerBase {
/**
* Initial environment of the player.
* @property {string} collision - Name of the current object the player is interacting with (e.g., 'floor', 'wall', 'platform').
* @property {Array} collisions - An array that holds a collection of player collisions.
* @property {string} animation - Name of the current animation state of the player (e.g., 'idle', 'walk', 'run', 'jump').
* @property {string} direction - The direction the player is facing (e.g., 'left', 'right').
* @property {Object} movement - The directions in which the player can move.
* @property {boolean} movement.up - Whether the player can move up.
* @property {boolean} movement.down - Whether the player can move down.
* @property {boolean} movement.left - Whether the player can move left.
* @property {boolean} movement.right - Whether the player can move right.
* @property {boolean} movement.falling - Whether the player is falling.
* @property {boolean} isDying - Whether the player is dying.
*/
// This object represents the initial state of the player when the game starts.
initEnvironmentState = {
// environment
collision: 'floor',
collisions: [],
// player
animation: 'idle',
direction: 'right',
movement: {up: false, down: false, left: true, right: true, falling: false},
isDying: false,
};
/** GameObject: Constructor for Player object
*/
constructor() {
this.state = {...this.initEnvironmentState}; // Player and environment states
}
}
// Create a new PlayerBase object
var player = new PlayerBase();
// Format the object as a string and display it
var msg = "Initial instance data for the player: " + JSON.stringify(player.state);
element.append(msg); // 'element.append' only works in Jupyter. Use 'console.log()' in a web environment.
// Spacing for the next output
element.append('<br><br>');
// 1st update to the "player's" instance data
player.state.collision = 'wall';
player.state.collisions.push(player.state.collision);
player.state.movement = {up: false, down: false, left: true, right: false, falling: false};
var msg1 = "1st update, wall collision simulation: " + JSON.stringify(player.state);
element.append(msg1);
// Spacing for the next output
element.append('<br><br>');
// 2nd update to the "player's" instance data
player.state.collision = 'jumpPlatform';
player.state.collisions.push(player.state.collision);
player.state.movement = {up: false, down: false, left: true, right: true, falling: false};
var msg2 = "2nd update, jumpPlatform collision simulation: " + JSON.stringify(player.state);
element.append(msg2);
// Spacing for the next output
element.append('<br><br>');
// 3rd update shows filtering out the last collision
player.state.collisions = player.state.collisions.filter(collision => collision !== player.state.collision);
player.state.collision = player.state?.collisions[0];
var msg3 = "3nd update, go back to the previous collision: " + JSON.stringify(player.state);
element.append(msg3);