Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - "object is not a function" when saving function.call to a variable

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...