Last active
January 15, 2020 14:35
-
-
Save adityardiansyah/a8500ca4d4302e19f97877851980e091 to your computer and use it in GitHub Desktop.
Dasar Object Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.