Dalam contoh ini, Anda akan belajar menulis program JavaScript yang akan memeriksa apakah suatu variabel berjenis fungsi.
Untuk memahami contoh ini, Anda harus memiliki pengetahuan tentang topik pemrograman JavaScript berikut:
- Jenis JavaScript dari Operator
- Panggilan Fungsi Javascript ()
- Objek Javascript toString ()
Contoh 1: Menggunakan contoh Operator
// program to check if a variable is of function type function testVariable(variable) ( if(variable instanceof Function) ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);
Keluaran
Variabel bukan tipe fungsi Variabel adalah tipe fungsi
Dalam program di atas, instanceof
operator digunakan untuk memeriksa jenis variabel.
Contoh 2: Menggunakan jenis Operator
// program to check if a variable is of function type function testVariable(variable) ( if(typeof variable === 'function') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);
Keluaran
Variabel bukan tipe fungsi Variabel adalah tipe fungsi
Pada program di atas, typeof
operator digunakan dengan ketat sama dengan ===
operator untuk mengecek jenis variabel.
The typeof
Operator memberikan tipe data variabel. ===
memeriksa apakah variabel tersebut sama dalam hal nilai serta tipe datanya.
Contoh 3: Menggunakan Metode Object.prototype.toString.call ()
// program to check if a variable is of function type function testVariable(variable) ( if(Object.prototype.toString.call(variable) == '(object Function)') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);
Keluaran
Variabel bukan tipe fungsi Variabel adalah tipe fungsi
The Object.prototype.toString.call()
method mengembalikan string yang menentukan jenis objek.