示例 1: 使用 instanceof 运算符
// 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);
输出
The variable is not of function type The variable is of function type
在上面的程序中,
instanceof
运算符用于检查变量的类型。
示例 2: 使用 typeof 运算符
// 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);
输出
The variable is not of function type The variable is of function type
在上面的程序中,
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);
输出
The variable is not of function type The variable is of function type
Object.prototype.toString.call()
方法返回一个指定对象类型的字符串。