繁体   English   中英

“回调不是函数”和function.apply()

[英]“callback is not the function” and function.apply()

为什么这根本行不通?

它说typeof(callback)= undefined。

function A(a,callback)
{
document.write(typeof(callback));  
callback();  
return a;  
}

function Run(func,args)
{

   return  func.apply(this||window, args || [
    function () { document.write("blah")}
  ]);

}


Run(A,[1]);

但是,在不使用function.apply的情况下,它可以正常运行:

function Run2(func,arg)
{

   return  func(arg,
    function () { document.write("blah")}
  );

}

Run2(A,1);

请耐心等待,我是JS新手。

该问题实际上是在带有callback变量的A函数中发生的。 如果您编写了如下的A函数,则不会收到此错误:

function A(a, callback) {
    var type = typeof callback;
    document.write(type);
    if(type == "function") callback();//ensure callback is a function
    return a;
}

apply的第一个参数是作用域,第二个参数是参数数组。 看来您有这个,但带有Run(A,[1]); args Run(A,[1]); 仅是一个与参数a对齐的参数(1),但是您缺少该函数。 在另一方面,如果args没有设置,您加入到用一个参数创建一个数组[ function ()... ]这将再次将对齐a

从外观上来看,你试图合并/串联这两个阵列的时候,其实|| 用作比较运算符,或用作or赋值。

尝试这个:

func.apply(this||window,args.concat([function () { document.write("blah")}]));

要么

args.push(function () { document.write("blah")});
func.apply(this||window,args);

apply()会将第一个参数,并使用它作为this函数调用,并使用第二个参数作为参数传递给该呼叫。 因此Run2像这样调用A(其中<func>是您的匿名函数):

A(1, <func>);

Run只在参数数组中传递一个参数1 ,然后像这样调用它:

A(1)

您要执行的操作是用以下命令替换“运行”(我认为):

function Run(func,args)
{
    args.push(function () { document.write("blah")});
    // args is now [1, function(){...}]
    return func.apply(this||window, args);
}

为了使Run()函数使用A() ,您需要2的数组长度,因为它需要两个参数。 您在args中只有1,如[1] 您需要[1, func] ,因此以下是您的解决方案:

// the keyword this always exists
function Run(func, args){
  args.push(func);
  return  func.apply(this, args || [function(){document.write("blah")}]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM