Métodos JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Ejemplo

const person = {
    firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + 
this.lastName;
  }
};

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>

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

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>

</body>
</html>

¿Qué es esto?

En JavaScript, la palabra clave this se refiere a un objeto.

Qué objeto depende de cómo se invoca (usa o llama) este.

La palabra clave this se refiere a diferentes objetos dependiendo de cómo se use:

  • En un método de objeto, this se refiere al objeto.

  • Por sí solo, este se refiere al objeto global.

  • En una función, this se refiere al objeto global.

  • En una función, en modo estricto, este es indefinido.

  • En un evento, este se refiere al elemento que recibió el evento.

  • Métodos como call(), apply() y bind() puede referir este a cualquier objeto.

Nota

este no es una variable. Es una palabra clave. No puedes cambiar el valor de this

Ver también:

El tutorial de JavaScript este


Métodos JavaScript

Los métodos de JavaScript son acciones que se pueden realizar sobre objetos.

Un método de JavaScript es una propiedad que contiene una función definición.

firstName

John

lastName

Gama

age

50

eyeColor

azul

fullName

función() {devolver este.primerNombre + " " + este.apellido;}

Los métodos son funciones almacenadas como propiedades de objetos.


Accediendo a métodos de objetos

Se accede a un método de objeto con la siguiente sintaxis:

objectName.methodName()

Normalmente describirá fullName() como un método del objeto persona, y fullName como propiedad.

La propiedad fullName se ejecutará (como una función) cuando se invoque con().

Este ejemplo accede al método fullName() de un objeto persona:

Ejemplo

name = person.fullName();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating and using an object method.</p>
<p>A method is actually a function definition stored as a property value.</p>

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

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

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

Si accede a la propiedad fullName, sin(), devolverá la definición de función:

Ejemplo

name = person.fullName;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>An object method is a function definition stored as a property value.</p>
<p>If you access it without (), it will return the function definition:</p>

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

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

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


Agregar un método a un objeto

Agregar un nuevo método a un objeto es fácil:

Ejemplo

 person.name = function () {
  return this.firstName + " " + this.lastName;
};

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
};
person.name = function() {
  return this.firstName + " " + this.lastName;
};

document.getElementById("demo").innerHTML =
"My father is " + person.name(); 
</script>

</body>
</html>

Usar métodos integrados

Este ejemplo utiliza el método toUpperCase() del objeto String, para convertir un texto a mayúsculas:

let message = "Hello world!";
let x = message.toUpperCase();

El valor de x, después de la ejecución del código anterior será:

HELLO WORLD!

Ejemplo

person.name = function () {
  return (this.firstName + " " + this.lastName).toUpperCase();
};

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
};
person.name = function() {
  return (this.firstName + " " + this.lastName).toUpperCase();
};

document.getElementById("demo").innerHTML =
"My father is " + person.name(); 
</script>

</body>
</html>