V tomto příkladu se naučíte psát program JavaScript, který ověří, zda je proměnná typu funkce.
Abyste pochopili tento příklad, měli byste znát následující programovací témata JavaScriptu:
- JavaScript typu operátora
- Volání funkce Javascript ()
- Objekt Javascript toString ()
Příklad 1: Použití instanceof 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);
Výstup
Proměnná není typu funkce Proměnná je typu funkce
Ve výše uvedeném programu se instanceofoperátor používá ke kontrole typu proměnné.
Příklad 2: Použití typeof 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);
Výstup
Proměnná není typu funkce Proměnná je typu funkce
Ve výše uvedeném programu se typeofoperátor používá s přísnou shodou s ===operátorem ke kontrole typu proměnné.
typeofOperátor poskytuje variabilní datový typ. ===zkontroluje, zda je proměnná stejná z hlediska hodnoty i datového typu.
Příklad 3: Použití metody 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);
Výstup
Proměnná není typu funkce Proměnná je typu funkce
Object.prototype.toString.call()Metoda vrátí řetězec, který určuje typ objektu.








