Función JavaScript aplicar() Método


Tabla de contenido

    Mostrar tabla de contenidos


Reutilización de métodos

Con el método apply(), puede escribir un método que pueda usarse en diferentes objetos.


El método JavaScript apply()

El método apply() es similar al método call() (capítulo anterior).

En este ejemplo, el método fullName de persona se aplica en persona1:

Ejemplo

const person = {
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
}

const person1 = {
  firstName: "Mary",
  lastName: "Doe"
}

// This will return "Mary Doe":
person.fullName.apply(person1);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p>In this example the fulllName method of person is <b>applied</b> on person1:</p>

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

<script>
const person = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

const person1 = {
  firstName:"John",
  lastName: "Doe"
}

document.getElementById("demo").innerHTML = person.fullName.apply(person1); 
</script>

</body>
</html>



La diferencia entre call() y apply()

La diferencia es:

El método call() toma argumentos por separado.

El método apply() toma argumentos como una matriz.

El método apply() es muy útil si desea utilizar una matriz en lugar de una lista de argumentos.


El método apply() con argumentos

El método apply() acepta argumentos en una matriz:

Ejemplo

const person = {
    fullName: function(city, country) {
    return this.firstName + " " + this.lastName 
  + "," + city + "," + country;
    }
}

const person1 = {
  firstName:"John",
    lastName: "Doe"
}

person.fullName.apply(person1, ["Oslo", "Norway"]);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p>In this example the fulllName method of person is <b>applied</b> on person1:</p>

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

<script>
const person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}

const person1 = {
  firstName:"John",
  lastName: "Doe"
}

document.getElementById("demo").innerHTML = person.fullName.apply(person1, ["Oslo", "Norway"]); 
</script>

</body>
</html>


Comparado con el método call():

Ejemplo

const person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName 
  + "," + city + "," + country;
    }
}

const person1 = {
    firstName:"John",
    lastName: "Doe"
}

person.fullName.call(person1, "Oslo", "Norway");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>
<p>This example calls the fullName method of person, using it on person1:
</p>

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

<script>
const person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}

const person1 = {
  firstName:"John",
  lastName: "Doe"
}

const person2 = {
  firstName:"Mary",
  lastName: "Doe"
}

document.getElementById("demo").innerHTML = person.fullName.call(person1, "Oslo", "Norway"); 
</script>

</body>
</html>




Simular un método Max en matrices

Puedes encontrar el número más grande (en una lista de números) usando el método Math.max():

Ejemplo

Math.max(1,2,3);  // Will return 3

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.max()</h2>
<p>This example returns the highest number in a list of number arguments:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max(1,2,3); 
</script>

</body>
</html>


Dado que las arrays de JavaScript no tienen un método max(), puede aplicar el método Math.max() en su lugar.

Ejemplo

Math.max.apply(null, [1,2,3]); // Will also return 3

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript apply()</h2>
<p>This example returns the highest number in an array of numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max.apply(null, [1,2,3]); 
</script>

</body>
</html>



El primer argumento (nulo) no importa. No se utiliza en este ejemplo.

Estos ejemplos darán el mismo resultado:

Ejemplo

Math.max.apply(Math, [1,2,3]); // Will also return 3

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript apply()</h2>
<p>This example returns the highest number in an array of numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max.apply(Math, [1,2,3]); 
</script>

</body>
</html>



Ejemplo

Math.max.apply(" ", [1,2,3]); // Will also return 3

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript apply()</h2>
<p>This example returns the highest number in an array of numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max.apply(" ", [1,2,3]); 
</script>

</body>
</html>



Ejemplo

Math.max.apply(0, [1,2,3]); // Will also return 3

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript apply()</h2>
<p>This example returns the highest number in an array of numbers:</p>

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

<script>
document.getElementById("demo").innerHTML = Math.max.apply(0, [1,2,3]); 
</script>

</body>
</html>




Modo estricto de JavaScript

En modo estricto de JavaScript, si el primer argumento del método apply() no es un objeto, se convierte en el propietario (objeto) de la función invocada. En modo "no estricto", se convierte en el objeto global.