V tem primeru se boste naučili pisati program JavaScript, ki bo preveril, ali je spremenljivka tipa funkcije.
Če želite razumeti ta primer, morate poznati naslednje teme programiranja JavaScript:
- JavaScript vrste operaterja
- Klic funkcije Javascript ()
- Javascript objekt toString ()
Primer 1: Uporaba instanceof operaterja
// 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);
Izhod
Spremenljivka ni tipa funkcije Spremenljivka ni funkcije
V zgornjem programu se z instanceof
operaterjem preveri vrsta spremenljivke.
Primer 2: Uporaba typeof operaterja
// 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);
Izhod
Spremenljivka ni tipa funkcije Spremenljivka ni funkcije
V zgornjem programu se za preverjanje vrste spremenljivke typeof
uporablja operator, ki je enak ===
operatorju.
typeof
Operater daje variabilno vrsto podatkov. ===
preveri, ali je spremenljivka enaka tako po vrednosti kot glede na tip podatkov.
Primer 3: Uporaba 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);
Izhod
Spremenljivka ni tipa funkcije Spremenljivka ni funkcije
Object.prototype.toString.call()
Metoda vrne niz, ki določa vrsto predmeta.