- Learn by example
Make an RPG
Vue Implementations

Examples of how to use Getters and Setters

Let's take a look at what using a class is like without explicitly using getters and setters.

class Monster { constructor( hp ) { this.hp = hp; } getHP() { return this.hp; } setHP( hp ) { this.hp = hp; } }

And, here's an example of how we use it:

var mon = new Monster(); mon.setHP( 50 ); var h = mon.getHP(); log( h );

With ES6's new getters and setters we can declare get or set in front of the function. That allows you to set and get values directly, like so:

class Monster { constructor( hp ) { this.hit_points = hp; } get hitp() { return this.hit_points; } set hitp( hp ) { this.hit_points = hp + 1; } }
var mon = new Monster(); mon.hitp = 35; log( mon.hitp );

As usual, go ahead and play around with the example code until it makes sense.

Try adding log statements to the getter and setters and constructor.
Try creating your own classes and or changing the variable names and setter/getter names.

In the next lesson, we will learn about Vue Basics

Get the Latest Tutorial Updates
<< >>