Using classes to create reusable objects
Sunday, Aug 9, 2020
JavaScript
JavaScript
Classes provide mechanism to easily create similar objects - users, game sprites, graphs, interfaces etc. Modern JavaScript makes it easier(compared to the method I described earlier) to define classes using the class and constructor keywords. New instances of the class can be created using new followed by class name.
constructoris called automatically each time a new instance of the class is created.- Arguments used while creating the new object are passed to the constructor. Arguments can be stored in
thisobject of the class. - Class methods can be simply created by writing functions without the
functionkeyword. - Methods can access properties and other methods using
thiskeyword.
class Pantry{
constructor(){
this.items = [];
}
getItems(){
return this.items;
}
addItem(item){
this.items.push(item);
}
removeItem(item){
this.items.splice(this.items.indexOf(item), 1);
return this.items;
}
howManyItems(){
return `there are ${this.items.length} items left in your pantry`;
}
}
// create a new object
const pantry = new Pantry();
console.log(pantry.getItems());
// []
pantry.addItem("cookies");
pantry.addItem("beans");
console.log(pantry.howManyItems());
// there are 2 items left in your pantry
console.log(pantry.getItems());
// [ 'cookies', 'beans' ]
pantry.removeItem("cookies");
console.log(pantry.getItems());
// [ 'beans' ]
console.log(pantry.howManyItems());
// there are 1 items left in your pantry
Use static method if it is not object specific
Using the keyword static in front of the method definition will allow to use the method on the class instead of object. This can be useful if the information is not object specific. For example, in the above case, if we want to limit the number of items in the pantry to 10, we could use a static method like so:
class Pantry{
...
static maxItems(){
return 10;
}
...
// static method is called on class and not object
isFull(){
return this.items.length === Pantry.maxItems();
}
}