9. Classes JavaScript classes are templates that consist of methods, variables, and inheritance. /* Create Class The following snippet will create a new class that will consist of methods and variables. */ class Fruit { constructor(name, color) { this._name = name; this._color = color; } eat() { console.log('You ate the ' + this.name + '.'); } get name() { return this._name; } set name(name) { this._name = name; } get color() { return this._color; } set color(color) { this._color = color; } } /* Create a new instance: */ let apple = new Fruit('Apple', 'Green'); /* Execute a method: */ apple.eat(); // Output: You ate the Apple. /* Get property: */ console.log(apple.color); // Output: Green /* Set property: */ apple.color = 'red'; console.log(apple.color); // Output: red /* Create a child class: */ class Orange extends Fruit { constructor() { super('Orange', 'Orange'); } throw() { console.log('You threw the ' + this.name + '.'); } } /* Create a new instance of the child class: */ let orange = new Orange(); orange.throw(); // Output: You threw the Orange. console.log(orange.color); // Output: Orange
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter