0% encontró este documento útil (0 votos)
25 vistas4 páginas

Clase Cuenta en JavaScript: Métodos y Atributos

El documento describe una clase Cuenta con atributos titular (obligatorio) y cantidad (opcional). Incluye constructores, métodos get, set y toString, e implementa métodos para ingresar y retirar montos de la cuenta. Se crea un objeto de la clase Cuenta y se prueban los métodos. Adicionalmente, incluye código HTML para crear un formulario para ingresar titular y cantidad.

Cargado por

Jessica Hinojosa
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
25 vistas4 páginas

Clase Cuenta en JavaScript: Métodos y Atributos

El documento describe una clase Cuenta con atributos titular (obligatorio) y cantidad (opcional). Incluye constructores, métodos get, set y toString, e implementa métodos para ingresar y retirar montos de la cuenta. Se crea un objeto de la clase Cuenta y se prueban los métodos. Adicionalmente, incluye código HTML para crear un formulario para ingresar titular y cantidad.

Cargado por

Jessica Hinojosa
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

Kevin Jhonatan Mamani Mollo

Ejercicio 1:
JS
/*
Crea una clase llamada Cuenta que tendrá los
siguientes atributos: titular y cantidad (puede tener
decimales).
El titular será obligatorio y la cantidad es
opcional. Crea dos constructores que cumpla lo anterior.
Crea sus métodos get, set y toString.
Tendrá dos métodos especiales:
ingresar(double cantidad): se ingresa una cantidad a
la cuenta, si la cantidad introducida es negativa, no se
hará nada.
retirar(double cantidad): se retira una cantidad a la
cuenta, si restando la cantidad actual a la que nos pasan
es negativa, la cantidad de la cuenta pasa a ser 0.
*/

class Cuenta {
titular;
cantidad;
constructor(titular, cantidad) {
[Link] = titular;
[Link] = cantidad;
}
titularRequired() {
[Link]([Link]);
if ([Link] == "") {
alert("El campo titular es obligatorio");
} else {
alert("Felicidades cumpliste con el campo requerido
de titular");
}
}
cantidadRequired() {
[Link]([Link]);
if (([Link] = null)) {
alert("El campo cantidad es obligatorio");
} else {
alert("Felicidades cumpliste con el campo requerido
de cantidad");
}
}
getTitular() {
[Link];
[Link];
alert(`El campo obtenido es titular: ${titular}`);
alert(`El campo obtenido es cantidad: ${cantidad}`);
}
setTitular(newTitular, newCantidad) {
[Link] = newTitular;
[Link] = newCantidad;
alert(`El campo seteado y su nuevo valor es:
${[Link]}`);
[Link]([Link]);
[Link](titular);
alert(`El campo seteado y su nuevo valor es:
${[Link]}`);
[Link]([Link]);
}
ingresarDouble(cantDouble) {
if ((cantDouble = 0 || cantDouble < 0)) {
[Link](
"Lo siento pero no se hace nada por ingresar numero
negativos"
);
} else {
[Link] + cantDouble;
}
}
retirar(monto) {
if ([Link] - monto < 0) {
[Link] = 0;
} else {
let saldoActual = [Link] - monto;
alert(`El monto retirado es: ${monto}`);
alert(`Su saldo actual es: ${saldoActual}`);
}
}
}
const objeto1 = new Cuenta("Kevin", 100);
//[Link]();
//[Link]();
//[Link]();
//[Link]("Juan", 10);
[Link](10.05);
[Link](20.3);

html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,
initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="" method="get">
<label for="">Ingrese titular*</label>
<input
type="text"
name=""
id="titular"
placeholder="Ingrese titular"
required
/>
<label for="">Ingrese cantidad</label>
<input
type="number"
name=""
id="cantidad"
placeholder="Ingrese cantidad"
/>
<input type="submit" value="Enviar" />
</form>
<script src="[Link]"></script>
</body>
</html>

Common questions

Con tecnología de IA

Improvements for reusability and error-proofing of the 'Cuenta' class could include: using comparison operators correctly (e.g., '==' or '===' instead of '='), encapsulating alert messages within more robust error handling techniques or returning error codes, and implementing checks or default values for parameters, especially optional ones. Additionally, using getter and setter methods can help standardize access to 'titular' and 'cantidad', ensuring they are always validated before any operation .

The methods 'titularRequired' and 'cantidadRequired' provide basic validation by outputting alerts if the fields are empty or 'null', though they contain logical errors. 'titularRequired' checks for an empty 'titular' and 'cantidadRequired' for a 'null' 'cantidad', issuing alerts accordingly. However, in 'cantidadRequired', the use of '=' instead of comparison operators to check for 'null' may result in incorrect validation execution .

When creating an instance of the "Cuenta" class, the key aspects to consider are that the 'titular' is mandatory, and the 'cantidad' is optional. The class has a constructor that requires a 'titular' as an argument and optionally accepts a 'cantidad'. When instantiating, ensure 'titular' is provided to avoid alerts indicating the field is required .

The 'setTitular' method sets both 'titular' and 'cantidad' without validation, potentially allowing unsafe values. To maintain data integrity, the method should validate inputs before setting them, ensuring 'titular' is not empty and 'cantidad' is a non-negative number. Implementing these checks prevents corrupted data or invalid states within 'Cuenta' instances .

Refactoring the "Cuenta" class to handle concurrency could involve using asynchronous programming constructs such as Promises or async/await to ensure that methods accessing shared resources (like 'cantidad') are synchronized. Additionally, implementing mutex locks or using atomic operations via features from Web Workers can effectively manage and serialize access to resources, preventing race conditions in concurrent scenarios .

Using alerts for validation in "Cuenta" can lead to poor user experience as alerts interrupt program flow and are intrusive. They also provide limited debugging information and cannot enforce rules (e.g., prevent form submission). Instead, returning boolean values or error messages can help handle errors programmatically, offering a smoother and more flexible validation approach .

The misuse of the assignment operator '=' instead of '==' results in logical errors that can lead to unintended behavior by setting variables within conditional statements, rather than comparing them. This could cause incorrect validation outcomes or failure to update internal states, impacting the functionality and reliability of the "Cuenta" class methods, as seen in 'ingresarDouble', where logic does not correctly prevent negative inputs .

The "retirar" method prevents the balance from being negative by checking if the result of 'this.cantidad - monto' is less than 0. If it is, the balance is set to 0. Otherwise, it subtracts 'monto' from 'cantidad' and updates the current balance. This prevents negative balances by ensuring the balance is reduced only if the result is non-negative .

The "ingresarDouble" method has a condition checking if the amount is 0 or negative, which is incorrectly implemented using assignment '=' instead of comparison '=='. This should be corrected to 'if (cantDouble <= 0)' to accurately check for non-positive values. Additionally, the method should update the 'cantidad' by using 'this.cantidad += cantDouble' to increase the balance .

The HTML form allows users to input 'titular' and 'cantidad', which are fields corresponding to "Cuenta" attributes. However, without JavaScript event handling in place, the form does not interact with the "Cuenta" methods, limiting its effectiveness. It lacks validation feedback or dynamic update of the created "Cuenta" object, necessitating better integration for full functionality .

También podría gustarte