I'm trying to solve a javascript exercise working with objects and classes, I'm not very good with this and I don't know if I did it right, did I do it right?
1- Extend the given class so that it implements a count() function that prints to the console the number of elements contained in the "value" property (do not modify the given constructor)
instantiate the class and call the new function count()
//Do not modify this constructor.
function Clase(elem){
this.valor = [];
this.valor['elem1'] = 1;
this.valor['elem2'] = 2;
this.valor['elem3'] = 3;
this.valor['elem4'] = elem;
}
my code =>
function Clase(elem){
this.valor = [];
this.valor['elem1'] = 1;
this.valor['elem2'] = 2;
this.valor['elem3'] = 3;
this.valor['elem4'] = elem;
}
class Extendida extends Clase{
contar(){
const keys = Object.keys(this.valor)
console.log(Object.keys(this.valor))
const keyslen = keys.length
return keyslen
}
}
const objeto = new Extendida(4)
objeto.contar()
Your code's contar() method correctly returns the number of properties in clase.valor. clase.valor is an Array that is getting dynamic properties. Dynamic properties are not the same as Array elements, however.
For example:
let a = [];
a['x'] = 10;
console.log(a.length); // 0
console.log(Object.keys(a)); // ['x']
console.log(Object.keys(a).length); // 1
But if you could change Clase constructor, you could use class keyword for the base class. Also, instead of using an Array for clase.valor, you could use a Map:
class Clase {
constructor(elem) {
this.valor = new Map([
['elem1', 1],
['elem2', 2],
['elem3', 3],
['elem4', elem],
]);
}
// abstract
contar() {
return 0;
}
}
Then Extendida:
class Extendida extends Clase {
// override
contar() {
const keys = Array.from(this.valor.keys())
console.log(keys)
const keyslen = this.valor.size
return keyslen
}
}
So, in real code sometimes you use either plain objects (or records), Array, Map, Set etc., but Array with dynamic properties is a confusing programming pattern.