Skip to content

Instantly share code, notes, and snippets.

@adityardiansyah
Last active January 15, 2020 14:35
Show Gist options
  • Save adityardiansyah/a8500ca4d4302e19f97877851980e091 to your computer and use it in GitHub Desktop.
Save adityardiansyah/a8500ca4d4302e19f97877851980e091 to your computer and use it in GitHub Desktop.
Dasar Object Javascript
// Construct Function
function Saya(nama, energi) {
this.nama = nama;
this.energi = energi;
this.makan = function(porsi){
this.energi += porsi;
},
this.main = function(jam) {
this.energi -= jam;
}
}
let aku = new Saya('Aditya', 10);
// Function Declaration
function Saya(nama, energi) {
let saya = {};
saya.nama = nama;
saya.energi = energi;
saya.makan = function(porsi){
this.energi += porsi;
},
saya.main = function(jam) {
this.energi -= jam;
}
return saya;
}
let aku = Saya('Aditya', 10);
// object literal
let saya = {
nama : "Aditya",
energi : 10,
makan : function(porsi){
this.energi = this.energi + porsi;
console.log(`Hallo ${this.nama}, Selamat Makan`);
},
main : function(jam) {
this.energi = this.energi - jam;
console.log(`Hallo ${this.nama}, Selamat Bermain`);
}
}
let dia = {
nama: "Dia",
energi: 10,
makan: function (porsi) {
this.energi = this.energi + porsi;
console.log(`Hallo ${this.nama}, Selamat Makan`);
},
main: function (jam) {
this.energi = this.energi - jam;
console.log(`Hallo ${this.nama}, Selamat Bermain`);
}
}
@adityardiansyah
Copy link
Author

Penjelasan
Object Literal disini jika kita ingin menampilkan banyak object, kita harus mendeklarasikan object nya di masing masing variabel.

Function Declaration disini jika kita mengola data di dalam fungsi kita harus menggunakan this atau window.

Construct Function disini sebenarnya hampir sama dengan Function Declaration, hanya ada deklarasi object dan return itu dihapus, dan di gantikan oleh new untuk menjalankan fungsinya.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment