ECMAScript 2015, también conocido como ES6, introdujo clases de JavaScript.
Las clases de JavaScript son plantillas para objetos de JavaScript.
Utilice la palabra clave class
para crear una clase.
Agregue siempre un método llamado constructor()
:
class ClassName {
constructor() { ... }
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
El ejemplo anterior crea una clase llamada "Coche".
La clase tiene dos propiedades iniciales: "nombre" y "año".
Una clase de JavaScript no es un objeto.
Es una plantilla para objetos JavaScript.
Cuando tienes una clase, puedes usar la clase para crear objetos:
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes</h1>
<p>Creating two car objects from a car class:</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
document.getElementById("demo").innerHTML =
myCar1.name + " " + myCar2.name;
</script>
</body>
</html>
El ejemplo anterior utiliza la clase Car para crear dos objetos Car.
El método constructor se llama automáticamente cuando se crea un nuevo objeto.
El método constructor es un método especial:
Tiene que tener el nombre exacto "constructor"
Se ejecuta automáticamente cuando se crea un nuevo objeto.
Se utiliza para inicializar las propiedades del objeto.
Si no define un método constructor, JavaScript agregará un método constructor vacío.
Los métodos de clase se crean con la misma sintaxis que los métodos de objeto.
Utilice la palabra clave class
para crear una clase.
Agregue siempre un método constructor()
.
Luego agregue cualquier número de métodos.
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Cree un método de clase llamado "edad", que devuelva la edad del automóvil:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Methods</h1>
<p>How to define and use a Class method.</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
const date = new Date();
return date.getFullYear() - this.year;
}
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>
</body>
</html>
Puede enviar parámetros a métodos de clase:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x - this.year;
}
}
const date = new Date();
let year = date.getFullYear();
const myCar = new
Car("Ford", 2014);
document.getElementById("demo").innerHTML=
"My car is
" + myCar.age(year) + " years old.";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Method</h1>
<p>Pass a parameter into the "age()" method.</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x - this.year;
}
}
const date = new Date();
let year = date.getFullYear();
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML=
"My car is " + myCar.age(year) + " years old.";
</script>
</body>
</html>
La siguiente tabla define la primera versión del navegador con soporte completo para Clases en JavaScript:
Chrome 49 | Edge 12 | Firefox 45 | Safari 9 | Opera 36 |
Mar, 2016 | Jul, 2015 | Mar, 2016 | Oct, 2015 | Mar, 2016 |
"use strict"
La sintaxis de las clases debe escribirse en "modo estricto".
Obtendrás un error si no sigue las reglas del "modo estricto".
En "modo estricto" obtendrá un error si utiliza una variable sin declarándolo:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
// date = new Date(); // This will not work
const date = new Date(); // This will work
return date.getFullYear() - this.year;
}
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes uses "strict mode"</h1>
<p>In a JavaScript Class you cannot use variable without declaring it.</p>
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
// date = new Date(); // This will not work
const date = new Date(); // This will work
return date.getFullYear() - this.year;
}
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>
</body>
</html>
Obtenga más información sobre el "modo estricto" en: Modo estricto JS.