În acest exemplu, veți învăța să scrieți un program JavaScript care va verifica dacă o variabilă este de tip funcție.
Pentru a înțelege acest exemplu, ar trebui să aveți cunoștințele despre următoarele subiecte de programare JavaScript:
- JavaScript de tip Operator
- Apel funcție Javascript ()
- Javascript Object toString ()
Exemplul 1: Utilizarea instanței 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);
Ieșire
Variabila nu este de tip funcție Variabila este de tip funcție
În programul de mai sus, instanceof
operatorul este utilizat pentru a verifica tipul de variabilă.
Exemplul 2: Utilizarea tipului de 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);
Ieșire
Variabila nu este de tip funcție Variabila este de tip funcție
În programul de mai sus, typeof
operatorul este utilizat cu strict egal cu ===
operatorul pentru a verifica tipul de variabilă.
typeof
Operatorul oferă tipul de date variabile. ===
verifică dacă variabila este egală din punct de vedere al valorii, precum și al tipului de date.
Exemplul 3: Utilizarea metodei 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);
Ieșire
Variabila nu este de tip funcție Variabila este de tip funcție
Object.prototype.toString.call()
Metoda returnează un șir de caractere care specifică tipul de obiect.