+ 3
How can I declare a class in JS?
Hi, I am trying to learn OOP with JS, so what is the right way to declare a JS class with constructor? =)
2 ответов
+ 10
An example of Class and inheritance in JavaScript in ES6 JS
class Animal {
constructor(nombre) {
this.nombre = nombre;
}
hablar() {
document.write(this.nombre + ' hace un ruido.');
}
}
class Perro extends Animal {
hablar() {
super.hablar();
document.write("<br>");
document.write(this.nombre + ' ladra.');
}
}
var p = new Perro('Mitzie');
p.hablar();
https://code.sololearn.com/WTLc0A3x0G27
+ 3
Classes were introduced in ES6 JS version. The syntax :
class Square {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
Just to add up: JS Classes are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. So I suggest you go through JS prototypal inheritance before the above just in case.