⊗jsOpBsCMS 20 of 60 menu

Class as a set of methods in OOP in JavaScript

Sometimes classes are used to group methods of similar topics. In this case, as a rule, only one object of this class is created and its methods are used many times in different situations.

Let's look at an example. Let's make a class that will manipulate arrays of numbers:

class ArrHelper { }

Each method of this class will take an array as a parameter and perform a given operation on it. Let's say, for example, we have the following methods:

class ArrHelper { getSum(arr) { // sum of elements } getAvg(arr) { // arithmetic mean arithmetical mean mean } }

Let's write the implementation of these methods:

class ArrHelper { getSum(arr) { let res = 0; for (let num of arr) { res += num; } return res; } getAvg(arr) { if (arr.length > 0) { let sum = this.getSum(arr); return sum / arr.length; } else { return 0; } } }

Let's see how we will use these methods. Let's create an object of our class:

let arrHelper = new ArrHelper;

Let's find the sum of numbers in different arrays using our object:

let sum1 = arrHelper.getSum([1, 2, 3]); console.log(sum1); let sum2 = arrHelper.getSum([3, 4, 5]); console.log(sum2);

Make a class Validator that will check strings for correctness.

Make a method isEmail in your class that checks if a string is a valid email.

Make a method isDomain in your class that checks whether a string is a valid domain name.

Create a method isNumber in your class that checks if a string contains only numbers.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline