我试图通过将函数缓存到变量来使我的代码更小。例如:
function test(){
var a = Array.prototype.slice,
b = a.call(arguments);
// Do something
setTimeout(function(){
var c = a.call(arguments);
// Do something else
}, 200);
}因此,我可以只调用a.call(arguments);,而不是调用Array.prototype.slice.call(arguments)。
我试图通过缓存Array.prototype.slice.call来使它变得更小,但这并不起作用。
function test(){
var a = Array.prototype.slice.call,
b = a(arguments);
// Do something
setTimeout(function(){
var c = a(arguments);
// Do something else
}, 200);
}这给了我TypeError: object is not a function。为什么会这样呢?
不出所料,typeof Array.prototype.slice.call返回"function"。
为什么我不能将.call保存到一个变量(然后调用它)?
发布于 2011-12-17 00:11:31
Function.prototype.call是一个普通函数,它对作为this传递的函数进行操作。
当你从一个变量调用call时,this变成了window,这不是一个函数。
您需要编写call.call(slice, someArray, arg1, arg2)
发布于 2011-12-17 00:09:26
试试这个:
function test(){
var a = function(args){
return Array.prototype.slice.call(args);
};
b = a(arguments);
// Do something
setTimeout(function(){
var c = a(arguments);
// Do something else
}, 200);
}如果您尝试执行以下操作,则会发生相同的错误:
var log = console.log;
log("Hello");原因是,当您这样做时,您将函数x (在我的示例log中)赋给变量log。但该函数包含对this的调用,该调用现在引用window而不是console,然后抛出错误this is not an object
发布于 2011-12-17 00:12:20
问题是call是一个方法(属于对象的函数),它希望它的所有者(它的this)是一个函数。当您编写a = Array.prototype.slice.call时,您复制的是函数,而不是所有者。
"object is not a function“消息并不是说a不是一个函数,而是说它的this不是一个函数。从技术上讲,您可以通过编写a.call(Array.prototype.slice, arguments)来实现您所描述的内容,但显然这不是您想要的!
https://stackoverflow.com/questions/8536847
复制相似问题