So I was making project and when I try to get the parameter from class parent its say NaN
while the other is true
.
Here the code:
class transportasi {//class parent
constructor(nama,roda,pintu){
this.nama = nama
this.roda = roda
this.pintu = pintu
}
}
class mobil extends transportasi{//Class Children
constructor(roda,lampu){
super(roda)//the problem
this.lampu = lampu
}
jmlahfeature(){
return this.lampu this.roda
}
}
const mobil1 = new mobil(2,4)//the problem
//I cant fill the value of roda only lampu
console.log("Hasil Perhitungan Feature mobil : " mobil1.jmlahfeature())
I want it so I can fill the value of parameter roda
. So it doesn't say NaN
in console.
CodePudding user response:
As Ivar points out correctly roda is the second parameter and you pass only the first parameter in the super().
The following code should give your desired result.
class transportasi {//class parent
constructor(nama,roda,pintu){
this.nama = nama
this.roda = roda
this.pintu = pintu
}
}
class mobil extends transportasi{//Class Children
constructor(roda,lampu){
super('here should be some value', roda)
this.lampu = lampu
}
jmlahfeature(){
return this.lampu this.roda
}
}
const mobil1 = new mobil(2,4)//the problem
//I cant fill the value of roda only lampu
console.log("Hasil Perhitungan Feature mobil : " mobil1.jmlahfeature())
CodePudding user response:
You did not assign any value to this.roda = roda
You can try this out.
class transportasi {//class parent
constructor(nama,roda,pintu){
this.nama = nama
this.roda = roda
this.pintu = pintu
}
}
class mobil extends transportasi{//Class Children
constructor(roda,lampu){
super(roda)//the problem
this.roda = roda
this.lampu = lampu
}
jmlahfeature(){
return this.lampu this.roda
}
}
const mobil1 = new mobil(2,4)//the problem
//I cant fill the value of roda only lampu
console.log("Hasil Perhitungan Feature mobil : " mobil1.jmlahfeature())
CodePudding user response:
Rather than individual arguments for the parent and child classes you supply a single object with named properties. A simple test within the child class can assign a default value if the required property has not been assigned to the parent arguments.
class transportasi {
constructor(args = {}) {
args = Object.assign({
nama: false,
roda: false,
pintu: false
}, args);
this.nama = args.nama;
this.roda = args.roda;
this.pintu = args.pintu;
}
}
class mobil extends transportasi {
constructor(args = {}) {
super(args)
this.lampu = args.lampu || 0;
}
jmlahfeature() {
return this.lampu this.roda
}
}
/* correctly named property - Maths should succeed */
const args = {
lampu: 2,
roda: 4
};
const app1 = new mobil(args);
console.log(app1.jmlahfeature());
/* incorrectly named, default value of zero used */
const bogus = {
xlamxpu: 23,
roda: 33
}
const app2 = new mobil(bogus);
console.log(app2.jmlahfeature());