跳到主要内容

JavaScript 程序:检查变量是否为函数类型

要理解这个示例,你应该具备以下 JavaScript 编程主题的知识:

示例 1:使用 instanceof 运算符

// 程序用于检查变量是否为函数类型

function testVariable(variable) {
if (variable instanceof Function) {
console.log("该变量是函数类型");
} else {
console.log("该变量不是函数类型");
}
}

const count = true;
const x = function () {
console.log("hello");
};

testVariable(count);
testVariable(x);

输出

该变量不是函数类型
该变量是函数类型

在上述程序中,使用了 instanceof 运算符来检查变量的类型。

示例 2:使用 typeof 运算符

// 程序用于检查变量是否为函数类型

function testVariable(variable) {
if (typeof variable === "function") {
console.log("该变量是函数类型");
} else {
console.log("该变量不是函数类型");
}
}

const count = true;
const x = function () {
console.log("hello");
};

testVariable(count);
testVariable(x);

输出

该变量不是函数类型
该变量是函数类型

在上述程序中,使用了 typeof 运算符与严格等于 === 运算符来检查变量的类型。

typeof 运算符给出变量的数据类型。=== 检查变量在值和数据类型上是否相等。

示例 3:使用 Object.prototype.toString.call() 方法

// 程序用于检查变量是否为函数类型

function testVariable(variable) {
if (Object.prototype.toString.call(variable) == "[object Function]") {
console.log("该变量是函数类型");
} else {
console.log("该变量不是函数类型");
}
}

const count = true;
const x = function () {
console.log("hello");
};

testVariable(count);
testVariable(x);

输出

该变量不是函数类型
该变量是函数类型

Object.prototype.toString.call() 方法返回一个指定对象类型的字符串。