W tym przykładzie nauczysz się pisać program JavaScript, który sprawdzi, czy zmienna jest typu funkcji.
Aby zrozumieć ten przykład, powinieneś znać następujące tematy programowania JavaScript:
- Operator JavaScript
- Wywołanie funkcji JavaScript ()
- Obiekt JavaScript toString ()
Przykład 1: Korzystanie z instanceof 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);
Wynik
Zmienna nie jest typu funkcji Zmienna jest typu funkcji
W powyższym programie instanceofoperator służy do sprawdzenia typu zmiennej.
Przykład 2: Korzystanie z operatora typeof
// 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);
Wynik
Zmienna nie jest typu funkcji Zmienna jest typu funkcji
W powyższym programie typeofoperator jest używany z ===operatorem ścisłej równości do sprawdzenia typu zmiennej.
typeofOperator daje zmienną typu danych. ===sprawdza, czy zmienna jest równa pod względem wartości i typu danych.
Przykład 3: Użycie metody 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);
Wynik
Zmienna nie jest typu funkcji Zmienna jest typu funkcji
Object.prototype.toString.call()Metoda zwraca ciąg znaków, który określa typ obiektu.








