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