I dette eksempel lærer du at skrive et JavaScript-program, der kontrollerer, om en variabel er af funktionstypen.
For at forstå dette eksempel skal du have kendskab til følgende JavaScript-programmeringsemner:
- JavaScript type af operatør
- Javascript-funktion kald ()
- Javascript-objekt tilString ()
Eksempel 1: Brug af instans af 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);
Produktion
Variablen er ikke af funktionstype Variablen er af funktionstype
I ovenstående program instanceof
bruges operatøren til at kontrollere typen af variabel.
Eksempel 2: Brug af 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);
Produktion
Variablen er ikke af funktionstype Variablen er af funktionstype
I ovenstående program typeof
bruges operatøren med nøjagtigt lig med ===
operatøren til at kontrollere typen af variabel.
Den typeof
operatør giver variable datatype. ===
kontrollerer, om variablen er lig med hensyn til værdi såvel som datatypen.
Eksempel 3: Brug af Object.prototype.toString.call () Metode
// 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);
Produktion
Variablen er ikke af funktionstype Variablen er af funktionstype
Den Object.prototype.toString.call()
metode returnerer en streng, der angiver objekttype.