JavaScript 新手。 我想检查 temp 是否是一个函数。另外我想知道为什么 typeof 在这种情况下不起作用:函数作为参数传递的情况。理解它是我的目的,所以请不要使用 jQuery。感谢所有的帮助。谢谢
function getParams(foo, bar) {
if (typeof bar === 'function') console.log("bar is a function");
console.log(typeof bar); // string: because i returned string. But why not a "function" ?
}
function temp(element) {
return element;
}
function runThis() {
getParams("hello", temp("world"));
}
runThis();
最佳答案
temp('world')
返回一个字符串,因此您传递的是字符串而不是函数。
您的意思是传入 temp
吗?
function getParams(foo, bar) {
if (typeof bar === 'function') console.log("bar is a function");
console.log(typeof bar); // string: because i returned string. But why not a "function" ?
}
function temp(element) {
return element;
}
function runThis() {
getParams("hello", temp("world")); // <-- temp("world") isn't a function. It's the result of a function
}
// Did you mean to do this?
function runThis2() {
getParams("hello", temp);
}
runThis();
runThis2();
如果您还想将参数传递给传入的函数,您可以这样做(有多种方法可以完成此操作):
function getParams(foo, bar, functionParam) {
if (typeof bar === 'function')
{
console.log("bar is a function");
const result = bar(functionParam);
console.log('function result: ', result);
}
console.log(typeof bar); // string: because i returned string. But why not a "function" ?
}
function temp(element) {
return element;
}
// Did you mean to do this?
function runThis2() {
getParams("hello", temp, 'my function param');
}
runThis2();
关于javascript - 检查作为参数传递的函数时,typeof 将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399132/