← All lessons/Objects· Lesson 28 of 32

Giving objects methods

Store a function inside an object so it can act on its own data.

About 7 min

A property that's a function

An object's value can be *anything* — including a function. A function stored on an object is called a method. Inside the method, the keyword this refers to the object itself, so this.x reads the object's own x.

let ball = {
  x: 200,
  y: 200,
  size: 100,
  draw: function () {
    ellipse(this.x, this.y, this.size, this.size);
  },
};
A ball that knows how to draw itself.

Calling a method

You call a method just like reading a property, but with parentheses on the end: ball.draw(). The dot tells the method *which* object's data to use.

Build the ball, then tell it to draw.

this

this inside ball.draw() means "this ball". So this.size is the same as ball.size — it just lets the method work no matter what the object is named.

Your turn

Add a method to the ball object. Give it a property named draw whose value is a function that calls ellipse(this.x, this.y, this.size, this.size). Then call the method with ball.draw().

Hints