Week 06 | Objects #
Inspiration #
Objects in JavaScript #
Objects are a handy way to encapsulate data and functions together. Or to be more precice we can create objects that have:
- different properties (like x, y, name etc.)
- property values stored into these properties (x:100, y:100, name:“Matti”).
- methods that are actions that can be performed on objects (functions of the object)
Take a look at the Objects tutorial from W3 School.
We could create and object called walker
that stores all the properties we need for a random walker that we have coded many times before in the class.
let walker = {x: 100, y: 100, s: 50, c: 255, name: "Matti"};
You can also write it like this. Linebreaks and spaces do not matter.
let walker = {
x: 100,
y: 100,
s: 50,
c: 255,
name: "Matti",
};
Accessing the properties of the object can be done using the dot syntax:
objectName.propertyName
In our case
walker.x
Then we can use these properties of the object in out code. For example, we can create two functions: moveWalker()
and drawWalker()
.
function moveWalker() {
walker.x = walker.x + random(-3, 3);
walker.y = walker.y + random(-3, 3);
}
function drawWalker() {
circle(walker.x, walker.y, walker.s);
textAlign(CENTER);
text(walker.name, walker.x, walker.y);
}
Here is the full code:
It is recommended to use
const
when you define and create an object. But I will generally just uselet
in this class to keep things simple.const walker = { x: 100, y: 100, s: 50, c: 255, name: "Matti", };
Methods #
In JavaScript we could also have functions encapsulated inside the objects, which is a very common way to use objects in JavaScript. Functions that are part of objects are called methods.
let walker = {
x: 100,
y: 100,
s: 50,
c: 255,
name: "Matti",
move: function(){
this.x = this.x + random(-3, 3);
this.y = this.y + random(-3, 3);
},
draw: function(){
circle(this.x, this.y, this.s);
textAlign(CENTER);
text(this.name, this.x, this.y);
}
};
And in our example, we could change the code like this to use these methods that are part of the walker object.
While this works just fine, we are not generally going to use methods in objects like this!
JavaScript has multiple ways to do many things, including how to work with objects. Adding methods like this in the objects works and you might see it used in other people’s code. However, we are going to do this in a slightly different way using classes. We are going to learn how classes work in the next lesson.
Examples #
Jump to the next lesson to see the examples we did in class about classes.