Selles näites õpid kirjutama JavaScripti programmi, mis kontrollib, kas muutuja on funktsiooni tüüpi.
Selle näite mõistmiseks peaksid teil olema teadmised järgmistest JavaScripti programmeerimise teemadest:
- Operaatori JavaScripti tüüp
- Javascripti funktsioonikõne ()
- Javascripti objekt toStringile ()
Näide 1: Operaatori instanceofi kasutamine
// 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);
Väljund
Muutuja ei ole funktsiooni tüüpi Muutuja on funktsiooni tüüpi
Ülaltoodud programmis instanceof
kasutatakse muutuja tüübi kontrollimiseks operaatorit.
Näide 2: Operaatori typeof kasutamine
// 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);
Väljund
Muutuja ei ole funktsiooni tüüpi Muutuja on funktsiooni tüüpi
Ülaltoodud programmis typeof
kasutatakse ===
muutujatüübi kontrollimiseks operaatorit operaatoriga võrdselt .
typeof
Operaator annab muutuja andmetüüp. ===
kontrollib, kas muutuja on väärtuselt ja andmetüübilt võrdne.
Näide 3: meetodi Object.prototype.toString.call () kasutamine
// 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);
Väljund
Muutuja ei ole funktsiooni tüüpi Muutuja on funktsiooni tüüpi
Object.prototype.toString.call()
Meetod tagastab stringi, mis määrab objekti tüübist.