Dans cet exemple, vous apprendrez à écrire un programme JavaScript qui vérifiera si une variable est de type fonction.
Pour comprendre cet exemple, vous devez avoir la connaissance des sujets de programmation JavaScript suivants:
- Opérateur JavaScript typeof
- Appel de fonction Javascript ()
- Objet Javascript toString ()
Exemple 1: Utilisation d'opérateur instanceof
// 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);
Production
La variable n'est pas de type fonction La variable est de type fonction
Dans le programme ci-dessus, l' instanceof
opérateur est utilisé pour vérifier le type de variable.
Exemple 2: Utilisation de 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);
Production
La variable n'est pas de type fonction La variable est de type fonction
Dans le programme ci-dessus, l' typeof
opérateur est utilisé avec l' opérateur strict égal à ===
pour vérifier le type de variable.
L' typeof
opérateur donne le type de données variable. ===
vérifie si la variable est égale en termes de valeur et de type de données.
Exemple 3: Utilisation de la méthode 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);
Production
La variable n'est pas de type fonction La variable est de type fonction
La Object.prototype.toString.call()
méthode renvoie une chaîne qui spécifie le type d'objet.