U ovom ćete primjeru naučiti pisati JavaScript program koji će provjeravati je li varijabla tipa funkcije.
Da biste razumjeli ovaj primjer, trebali biste imati znanje o sljedećim temama programiranja JavaScript:
- JavaScript vrsta operatora
- Poziv funkcije Javascript ()
- Javascript objekt toString ()
Primjer 1: Korištenje instanceof Operatora
// 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);
Izlaz
Varijabla nije tipa funkcije Varijabla je tipa funkcije
U gore navedenom programu instanceof
operator se koristi za provjeru vrste varijable.
Primjer 2: Korištenje typeof Operatora
// 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);
Izlaz
Varijabla nije tipa funkcije Varijabla je tipa funkcije
U gore navedenom programu, typeof
operator se koristi sa strogo jednakim ===
operatoru za provjeru vrste varijable.
typeof
Operater daje varijablu vrstu podataka. ===
provjerava je li varijabla jednaka u smislu vrijednosti kao i tipa podataka.
Primjer 3: Korištenje 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);
Izlaz
Varijabla nije tipa funkcije Varijabla je tipa funkcije
Object.prototype.toString.call()
Metoda vraća string koji određuje tip objekta.