Програма JavaScript для перевірки наявності змінної типу функції

У цьому прикладі ви навчитеся писати програму JavaScript, яка перевірятиме, чи є змінна типом функції.

Щоб зрозуміти цей приклад, ви повинні знати такі теми програмування JavaScript:

  • Тип оператора JavaScript
  • Виклик функції Javascript ()
  • Об'єкт Javascript toString ()

Приклад 1: Використання 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);

Вихідні дані

 Змінна не має типу функції Змінна має тип функції

У наведеній вище програмі instanceofоператор використовується для перевірки типу змінної.

Приклад 2: Використання 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);

Вихідні дані

 Змінна не має типу функції Змінна має тип функції

У наведеній вище програмі для перевірки типу змінної typeofвикористовується оператор із строгим рівним ===оператору.

typeofОператор дає тип змінного даних. ===перевіряє, чи є змінна рівною як за значенням, так і за типом даних.

Приклад 3: Використання методу 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);

Вихідні дані

 Змінна не має типу функції Змінна має тип функції 

Object.prototype.toString.call()Метод повертає рядок , яка визначає тип об'єкта.

Цікаві статті...