所以我做了一个项目,当我试图从类的父类获取参数时,它说是NaN,而另一个是true。在这里,代码:
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())
我想要它,这样我就可以填充参数roda的值。所以它没有在控制台中说NaN。
发布于 2022-11-28 09:05:21
正如伊瓦尔所指出的,roda是第二个参数,并且您只传递了超级()中的第一个参数。
下面的代码应该给出您想要的结果。
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())发布于 2022-11-28 09:16:58
您没有为this.roda = roda分配任何值,您可以尝试使用此方法。
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())发布于 2022-11-28 09:24:27
而不是为父类和子类提供单个参数,而是提供一个具有命名属性的对象。如果未将所需的属性分配给父参数,则子类中的简单测试可以分配默认值。
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());
https://stackoverflow.com/questions/74598144
复制相似问题