javascript - 检查作为参数传递的函数时,typeof 将不起作用

标签 javascript typeof

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/

相关文章:

python - 确定对象的类型?

c++ - If-else 基于正在使用的 typedef

javascript - 仅允许在 View 和模型值中使用字母字符的指令

javascript - 在 AngularJS 中结合 2 个 Promise

javascript - 根据表中的另一列更改按钮颜色

java - 在 Java 中判断一个数字是否为 Double

javascript - 为什么 typeahead-js 不能在 Meteor 上运行,但可以在本地运行?

javascript - Angular JS - $q.all() 跟踪个人上传进度

Javascript 类型比较

c# - 遍历类和子类以在 C# 中检索属性和值