„JavaScript“ programa, skirta patikrinti, ar kintamasis yra funkcijos tipo

Šiame pavyzdyje išmoksite rašyti „JavaScript“ programą, kuri patikrins, ar kintamasis yra funkcijos tipo.

Norėdami suprasti šį pavyzdį, turite žinoti šias „JavaScript“ programavimo temas:

  • Operatoriaus „JavaScript“ tipas
  • „Javascript“ funkcijų iškvietimas ()
  • „Javascript Object toString“ ()

1 pavyzdys: Operatoriaus egzemplioriaus naudojimas

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

Rezultatas

 Kintamasis nėra funkcijos tipo. Kintamasis yra funkcijos tipo

Pirmiau pateiktoje programoje instanceofoperatorius naudojamas kintamojo tipui patikrinti.

2 pavyzdys: Operatoriaus tipo naudojimas

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

Rezultatas

 Kintamasis nėra funkcijos tipo. Kintamasis yra funkcijos tipo

Pirmiau pateiktoje programoje kintamojo tipui patikrinti typeofoperatorius naudojamas griežtai lygus ===operatoriui.

typeofOperatorius suteikia kintamą duomenų tipą. ===tikrina, ar kintamasis yra lygus pagal vertę ir duomenų tipą.

3 pavyzdys: metodo „Object.prototype.toString.call ()“ naudojimas

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

Rezultatas

 Kintamasis nėra funkcijos tipo. Kintamasis yra funkcijos tipo 

Object.prototype.toString.call()Metodas grąžina eilutę, nurodantį objekto tipą.

Įdomios straipsniai...