JavaScript-program for å sjekke om en variabel er av funksjonstype

I dette eksemplet lærer du å skrive et JavaScript-program som sjekker om en variabel er av funksjonstype.

For å forstå dette eksemplet, bør du ha kunnskap om følgende JavaScript-programmeringsemner:

  • JavaScript-type av operatør
  • Javascript Funksjon samtale ()
  • Javascript Object toString ()

Eksempel 1: Bruke forekomst 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);

Produksjon

 Variabelen er ikke av funksjonstype Variabelen er av funksjonstype

I programmet ovenfor instanceofbrukes operatøren til å sjekke typen variabel.

Eksempel 2: Bruk type 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);

Produksjon

 Variabelen er ikke av funksjonstype Variabelen er av funksjonstype

I det ovennevnte programmet brukes typeofoperatøren med strengt lik ===operatøren for å sjekke typen variabel.

Den typeofOperatøren gir den variable datatype. ===sjekker om variabelen er lik både når det gjelder verdi og datatype.

Eksempel 3: Bruk av 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);

Produksjon

 Variabelen er ikke av funksjonstype Variabelen er av funksjonstype 

Den Object.prototype.toString.call()metoden returnerer en streng som angir objekttype.

Interessante artikler...