“对象不是功能"指的是对象不是功能.当保存function.call到变量时 [英] "object is not a function" when saving function.call to a variable

查看:37
本文介绍了“对象不是功能"指的是对象不是功能.当保存function.call到变量时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过将函数缓存到变量来使代码更小.例如:

 功能测试(){var a = Array.prototype.slice,b = a.call(参数);//做一点事setTimeout(function(){var c = a.call(arguments);//做其他事情},200);} 

因此,我不必执行 a.call(arguments); .而不是调用 Array.prototype.slice.call(arguments).

我试图通过缓存 Array.prototype.slice.call 来使其更小,但这是行不通的.

 功能测试(){var a = Array.prototype.slice.call,b = a(参数);//做一点事setTimeout(function(){var c = a(arguments);//做其他事情},200);} 

这给了我 TypeError:object不是一个函数.为什么会这样?

Array.prototype.slice.call 的类型返回功能" ,与预期的一样.

为什么不能将 .call 保存到变量(然后调用它)?

解决方案

Function.prototype.call 是一个普通函数,对作为 this 传递的函数进行操作./p>

从变量调用 call 时,变为 window ,这不是函数.
您需要编写 call.call(slice,someArray,arg1,arg2)

I was trying to make my code smaller by caching functions to variables. For example:

function test(){
   var a = Array.prototype.slice,
   b = a.call(arguments);
   // Do something
   setTimeout(function(){
     var c = a.call(arguments);
     // Do something else
   }, 200);
}

So instead of calling Array.prototype.slice.call(arguments), I can just do a.call(arguments);.

I was trying to make this even smaller by caching Array.prototype.slice.call, but that wasn't working.

function test(){
   var a = Array.prototype.slice.call,
   b = a(arguments);
   // Do something
   setTimeout(function(){
     var c = a(arguments);
     // Do something else
   }, 200);
}

This gives me TypeError: object is not a function. Why is that?

typeof Array.prototype.slice.call returns "function", like expected.

Why can't I save .call to a variable (and then call it)?

解决方案

Function.prototype.call is an ordinary function that operates on the function passed as this.

When you call call from a variable, this becomes window, which is not a function.
You need to write call.call(slice, someArray, arg1, arg2)

这篇关于“对象不是功能"指的是对象不是功能.当保存function.call到变量时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆