Panggilan Fungsi JavaScript
Metode Penggunaan Kembali
Dengan call()
metode, Anda dapat menulis metode yang dapat digunakan pada objek yang berbeda.
Semua Fungsi adalah Metode
Dalam JavaScript semua fungsi adalah metode objek.
Jika suatu fungsi bukan metode dari objek JavaScript, itu adalah fungsi dari objek global (lihat bab sebelumnya).
Contoh di bawah ini membuat objek dengan 3 properti, FirstName, LastName, FullName.
Contoh
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
// This will return "John Doe":
myObject.fullName();
Kata Kunci ini
Dalam definisi fungsi, this
mengacu pada "pemilik" fungsi.
Pada contoh di atas, this
adalah objek person yang "memiliki"
fungsi fullName .
Dengan kata lain, this.firstName berarti properti firstName dari objek ini .
Baca lebih lanjut tentang this
kata kunci di JS Kata Kunci ini .
Panggilan JavaScript () Metode
Metode call()
ini adalah metode JavaScript yang telah ditentukan sebelumnya.
Ini dapat digunakan untuk memanggil (memanggil) metode dengan objek pemilik sebagai argumen (parameter).
Dengan call()
, suatu objek dapat menggunakan metode milik objek lain.
Contoh ini memanggil metode fullName orang, menggunakannya pada person1 :
Contoh
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
// This will return "John Doe":
person.fullName.call(person1);
Contoh ini memanggil metode fullName orang, menggunakannya pada person2 :
Contoh
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
// This will return "Mary Doe"
person.fullName.call(person2);
Metode call() dengan Argumen
Metode call()
ini dapat menerima argumen:
Contoh
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName
+ "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.call(person1, "Oslo", "Norway");