JavaScript-programma om te controleren of een variabele van het functietype is

In dit voorbeeld leert u een JavaScript-programma te schrijven dat controleert of een variabele van het functietype is.

Om dit voorbeeld te begrijpen, moet u kennis hebben van de volgende JavaScript-programmeeronderwerpen:

  • JavaScript-type Operator
  • Javascript-functieaanroep ()
  • Javascript-object toString ()

Voorbeeld 1: instanceof Operator gebruiken

 // 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);

Uitvoer

 De variabele is niet van het functietype. De variabele is van het functietype

In het bovenstaande programma wordt de instanceofoperator gebruikt om het type variabele te controleren.

Voorbeeld 2: Type Operator gebruiken

 // 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);

Uitvoer

 De variabele is niet van het functietype. De variabele is van het functietype

In het bovenstaande programma wordt de typeofoperator gebruikt met strikt gelijk aan ===operator om het type variabele te controleren.

De typeofoperator geeft het variabele gegevenstype. ===controleert of de variabele gelijk is in termen van waarde en het gegevenstype.

Voorbeeld 3: de methode Object.prototype.toString.call () gebruiken

 // 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);

Uitvoer

 De variabele is niet van het functietype. De variabele is van het functietype 

De Object.prototype.toString.call()methode retourneert een tekenreeks die het objecttype specificeert.

Interessante artikelen...