settingsAccountsettings
Menusettings

Q: What are classes in JavaScript?

+1 vote
Can you please explain the class in JavaScript (its usage and definition)? Maybe give some examples as well. Thank you.
asked in JavaScript category by user andrew

1 Answer

0 votes

In programming classes provide the structure for objects

  • Act as template for objects of the same type

Classes define:

  • Data (properties, attributes), e.g. width, height, color
  • Actions (behavior), e.g. calcArea(), resize(ratio)

In 2 words: the class in JavaScript is: data (properties) + actions (methods) over this data.

One class may have many instances (objects).

Example:

class Rectangle {
    constructor(width, height, color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }
}
let redRect = new Rectangle(4, 5, 'red');
let blueRect = new Rectangle(8, 3, 'blue');
console.log(redRect);
console.log(blueRect);

Methods perform operations over the class data - example (methods are in lines 8 and 12 (highlighted)):

class Rectangle {
    constructor(width, height, color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    calcArea() {
        return this.width * this.height;
    }

    resize(ratio) {
        this.width = this.width * ratio;
        this.height = this.height * ratio;
    }
}
let rect = new Rectangle(4, 5, 'red');
console.log(rect.calcArea());//20
rect.resize(2);
console.log(rect.calcArea());//80 (width = 8; height = 10; (8*10=80))

Classes Vs. Objects in JavaScript:

classes and objects in javascript

answered by user eiorgert
edited by user eiorgert
...