21 JavaScript Code Snippets for Beginners - Classes
Thu Dec 29 2022 20:28:09 GMT+0000 (Coordinated Universal Time)
Saved by
@RLMA2
#javascript
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
content_copyCOPY
https://codeshack.io/21-javascript-code-snippets-beginners/#classes
Comments