I det här exemplet lär du dig att skriva ett JavaScript-program som kontrollerar om en variabel är av funktionstyp.
För att förstå detta exempel bör du ha kunskap om följande JavaScript-programmeringsämnen:
- JavaScript-typ av operatör
- Javascript-funktionsanrop ()
- Javascript Object toString ()
Exempel 1: Använd instans av operatör
// 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);
Produktion
Variabeln är inte av funktionstyp Variabeln är av funktionstyp
I ovanstående program används instanceof
operatören för att kontrollera typen av variabel.
Exempel 2: Använd typ av operatör
// 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);
Produktion
Variabeln är inte av funktionstyp Variabeln är av funktionstyp
I ovanstående program används typeof
operatören med strikt lika med ===
operatören för att kontrollera typen av variabel.
Den typeof
operatör ger typen den variabla data. ===
kontrollerar om variabeln är lika med avseende på värde såväl som datatyp.
Exempel 3: Använda Object.prototype.toString.call () -metoden
// 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);
Produktion
Variabeln är inte av funktionstyp Variabeln är av funktionstyp
Den Object.prototype.toString.call()
metod returnerar en sträng som anger objekttypen.