【问题标题】:typeof won't work when checking a function that's passed as a parameter [duplicate]检查作为参数传递的函数时,typeof 不起作用 [重复]
【发布时间】:2020-02-12 09:33:01
【问题描述】:

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

【问题讨论】:

  • 你传递的不是函数,而是调用函数的结果。
  • @DaveNewton 是的,您正在传递一个返回值。这是一个字符串。
  • 谢谢戴夫。有没有办法纯粹传递函数,而不是调用函数的结果?
  • getParams("hello", temp);
  • 要传递带参数的函数,请传递一个匿名函数,该函数使用所需的参数调用您的函数:getParams("hello", function() { temp("world"); });

标签: javascript typeof


【解决方案1】:

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

【讨论】:

  • 啊……我明白了。谢谢。但我需要将参数传递给 temp 函数。如: getParams(a1, a2, temp(a1,a2,"value")) 来检查。 a1 和 a2 需要传递给函数,“temp”作为参数。
  • 是的,我会这样做。谢谢。如果我这样做,我不知道我正在传递一个函数的结果。
猜你喜欢
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 2019-07-23
  • 2011-04-07
  • 1970-01-01
相关资源
最近更新 更多