Penggunaan Class
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
// cara membuat class
// 1. sintaksi dengan function
function Mail() {
this.from = '[email protected]';
}
Mail.prototype.sendMessage = function n(msg, to) {
console.log(`you send: ${msg} to ${to} from ${this.from}`);
}
// menggunakan prototype
const mail = new Mail();
console.log(mail.hasOwnProperty('sendMessage'));
// hasilnya = false
function Mail2(){
this.from = "[email protected]",
this.sendMessage = function(msg, to) {
console.log(`you send: ${msg} to ${to} from ${this.from}`);
}
}
// tanpa prototype
const mail1 = new Mail2();
console.log(mail1.hasOwnProperty('sendMessage'));
// Ketika kita meng-instantiate objek-objek lain, objek yang menggunakan prototype tidak meng-copy atribut sendMessage
// ke setiap objek-objek.
// Berbeda ketika kita tidak menggunakan prototype, semua attribute di-copy ke setiap objek. Dengan demikian,
// penggunaan prototype dapat menghemat alokasi memori yang digunakan.
// 2. menggunakan sintaksis class.
class Mail3 {
constructor() {
this.from = '[email protected]';
}
sendMessage(msg, to) {
console.log(`you send: ${msg} to ${to} from ${this.from}`);
}
}
const mail3 = new Mail3()
mail3.sendMessage('hallo', '[email protected]');
console.log(mail3.hasOwnProperty('sendMessage'));
// Cara kedua pada dasarnya menggunakan prototype,
// penggunaan sintaksis class pada javascript hanyalah syntactic sugar dari prototype itu sendiri.
JavaScript
INFO