Herencia de clases de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Herencia de clase

Para crear una herencia de clases, utilice extend palabra clave.

Una clase creada con una herencia de clases hereda todos los métodos de otra clase:

Ejemplo

Cree una clase llamada "Modelo" que heredará los métodos del "Coche" clase:

class Car {
  constructor(brand) {
    this.carname = 
  brand;	  }
  present() {
    return 'I have a ' + this.carname;	  }
}
class Model extends Car {	  constructor(brand, mod) {
    super(brand);
    this.model = mod;	  }
  show() {
   
      return this.present() + ', it is a ' + this.model;	  }
}
let myCar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML 
  = myCar.show();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Inheritance</h1>

<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>

<p id="demo"></p>

<script>
class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}

const myCar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = myCar.show();
</script>

</body>
</html>

El método super() se refiere al padre clase.

Llamando al método super() en el método constructor, llamamos al método constructor del padre y obtenemos acceso a las propiedades y métodos de los padres.

La herencia es útil para la reutilización del código: reutilice las propiedades y métodos de una clase existente al crear una nueva clase.



Captadores y definidores

Las clases también te permiten utilizar captadores y definidores.

Puede ser inteligente utilizar captadores y definidores para sus propiedades, especialmente si quieres hacer algo especial con el valor antes de devolverlos, o antes tú los configuras.

Para agregar captadores y definidores en la clase, use obtener y set palabras clave.

Ejemplo

Cree un captador y un definidor para la propiedad "carname":

 class Car {
  constructor(brand) {
    this.carname 
  = brand;
  }
  get cnam() {
    
  return this.carname;
  }
  set cnam(x) {
    
  this.carname = x;
  }
}
const myCar = new Car("Ford");

  document.getElementById("demo").innerHTML = myCar.cnam;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Getter/Setter</h1>
<p>A demonstration of how to add getters and setters in a class, and how to use the getter to get the property value.</p>

<p id="demo"></p>

<script>
class Car {
  constructor(brand) {
    this.carname = brand;
  }
  get cnam() {
    return this.carname;
  }
  set cnam(x) {
    this.carname = x;
  }
}

const myCar = new Car("Ford");

document.getElementById("demo").innerHTML = myCar.cnam;
</script>

</body>
</html>

Nota: incluso si el captador es un método, no utiliza paréntesis cuando desea obtener el valor de la propiedad.

El nombre del método getter/setter no puede ser el mismo que el nombre del propiedad, en este caso carname.

<p>Muchos programadores utilizan un carácter de subrayado _ antes del nombre de la propiedad para separar el captador/definidor de la propiedad real:

Ejemplo

Puede utilizar el carácter de subrayado para separar el captador/definidor del propiedad real:

 class Car {
  constructor(brand) {
    this._carname 
  = brand;
  }
  get carname() {
    
  return this._carname;
  }
  set carname(x) {
    
  this._carname = x;
  }
}
const myCar = new Car("Ford");

  document.getElementById("demo").innerHTML = myCar.carname;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Getter/Setter</h1>
<p>Using an underscore character is common practice when using getters/setters in JavaScript, but not mandatory, you can name them anything you like, but not the same as the property name.</p>

<p id="demo"></p>

<script>
class Car {
  constructor(brand) {
    this._carname = brand;
  }
  get carname() {
    return this._carname;
  }
  set carname(x) {
    this._carname = x;
  }
}

const myCar = new Car("Ford");

document.getElementById("demo").innerHTML = myCar.carname;
</script>

</body>
</html>

Para usar un definidor, use la misma sintaxis que cuando establece un valor de propiedad, sin paréntesis:

Ejemplo

Utilice un configurador para cambiar el nombre del coche a "Volvo":

 class Car {
  constructor(brand) {
    this._carname 
  = brand;
  }
  get carname() {
    
  return this._carname;
  }
  set carname(x) {
    
  this._carname = x;
  }
}
const myCar = new Car("Ford");
  myCar.carname = "Volvo";
  document.getElementById("demo").innerHTML = myCar.carname;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Class Setters</h1>
<p>When using a setter to set a property value, you do not use parantheses.</p>

<p id="demo"></p>

<script>
class Car {
  constructor(brand) {
    this._carname = brand;
  }
  set carname(x) {
    this._carname = x;
  }
  get carname() {
    return this._carname;
  }
}

const myCar = new Car("Ford");
myCar.carname = "Volvo";
document.getElementById("demo").innerHTML = myCar.carname;
</script>

</body>
</html>

Izar

A diferencia de las funciones y otras declaraciones de JavaScript, las declaraciones de clases no se elevan.

Eso significa que debes declarar una clase antes de poder usarla:

Ejemplo

 //You cannot use the class yet.
//myCar = new Car("Ford") will raise an error.
class Car {	  constructor(brand) {
    this.carname = brand;	  }
}
//Now you can use the class:
const myCar = new Car("Ford")

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Classes are not Hoisted</h1>
<p>You will get an error if you try to use a class before it is declared.</p>

<p id="demo"></p>

<script>
//You cannot use the class yet.
//myCar = new Car("Ford") will raise an error.

class Car {
  constructor(brand) {
    this.carname = brand;
  }
}

//Now you can use the class:
const myCar = new Car("Ford");
document.getElementById("demo").innerHTML = myCar.carname;

</script>

</body>
</html>

Nota: Para otras declaraciones, como funciones, NO obtendrá una error cuando intentas usarlo antes de que se declare, porque el comportamiento predeterminado de las declaraciones de JavaScript están aumentando (moviendo la declaración a la parte superior).