Programa JavaScript para comprobar si una variable es de tipo de función

En este ejemplo, aprenderá a escribir un programa JavaScript que comprobará si una variable es del tipo de función.

Para comprender este ejemplo, debe tener el conocimiento de los siguientes temas de programación de JavaScript:

  • Operador de tipo JavaScript
  • Llamada a la función Javascript ()
  • Objeto Javascript toString ()

Ejemplo 1: uso de 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);

Salida

 La variable no es de tipo de función La variable es de tipo de función

En el programa anterior, el instanceofoperador se usa para verificar el tipo de variable.

Ejemplo 2: uso 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);

Salida

 La variable no es de tipo de función La variable es de tipo de función

En el programa anterior, el typeofoperador se usa con estricto ===operador igual a para verificar el tipo de variable.

El typeofoperador da el tipo de datos de la variable. ===comprueba si la variable es igual en términos de valor y tipo de datos.

Ejemplo 3: Uso del método 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);

Salida

 La variable no es de tipo de función La variable es de tipo de función 

El Object.prototype.toString.call()método devuelve una cadena que especifica el tipo de objeto.

Articulos interesantes...