I want to ask why I get an error when I want to include a function in a class?
Is there any other way to include the function inside the class?
class Barang {
constructor(Nama, Harga, Merk) {
this.Nama = Nama;
this.Harga = Harga;
this.Merk = Merk;
}
}
class Kategori extends Barang {
constructor(Nama, Harga, Merk, Kategori, Jenis) {
super(Nama, Harga, Merk);
this.Kategori = Kategori;
this.Jenis = Jenis;
}
function Ongkir(berat) {
var berat = berat;
var biaya = function (){
return berat * 8000
}
this.totalBiaya = function () {
return biaya()
}
}
}
**Thank you in advance
CodePudding user response:
Remove the function
keyword
class Barang {
constructor(Nama, Harga, Merk) {
this.Nama = Nama;
this.Harga = Harga;
this.Merk = Merk;
}
}
class Kategori extends Barang {
constructor(Nama, Harga, Merk, Kategori, Jenis) {
super(Nama, Harga, Merk);
this.Kategori = Kategori;
this.Jenis = Jenis;
}
Ongkir(berat) {
var berat = berat;
var biaya = function (){
return berat * 8000
}
this.totalBiaya = function () {
return biaya()
}
}
}
var test = new Kategori();
console.log(test.Ongkir());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
To define a function inside the class, just set the name. And pay attention that you don't need to use the keyword function || const
before the name.
P.S. You forgot to close a curly bracket.
class Barang {
constructor(Nama, Harga, Merk) {
this.Nama = Nama;
this.Harga = Harga;
this.Merk = Merk;
};
};
class Kategori extends Barang {
constructor(Nama, Harga, Merk, Kategori, Jenis) {
super(Nama, Harga, Merk);
this.Kategori = Kategori;
this.Jenis = Jenis;
};
Ongkir(berat) {
var berat = berat;
var biaya = function() {
return berat * 8000
};
this.totalBiaya = function() {
return biaya()
};
};
};
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>