你如何引用Array.prototype.slice.call()? [英] How do you reference Array.prototype.slice.call()?

查看:78
本文介绍了你如何引用Array.prototype.slice.call()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,我需要在许多不同的地方克隆数组。出于这个原因,我想执行以下操作来模拟克隆函数:

I am writing a script in which I need to clone arrays in many different places. For this reason, I would like to do the following to emulate a cloning function:

var clone = [].slice.call;
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = clone(arr1, 0);

不幸的是,上面的代码导致: TypeError:object不是函数。我意识到有许多功能可以做深度克隆和浅拷贝,但我只是想使用内置方法。有趣的是,以下内容确实有效:

Unfortunately, the above code results in: TypeError: object is not a function. I realize there are many functions out there to do deep cloning and shallow copies but I just want to use the built in method. Interestingly enough, the following does work:

var clone = [].slice;
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = clone.call(arr1, 0);

有人知道为什么第一个块不起作用而第二个块不起作用?有没有办法在调用引用函数时引用函数调用和应用函数而不抛出错误?

Does anyone know why the first block doesn't work while the second does? Is there any way to reference a functions call and apply functions without throwing errors when calling the referenced function?

推荐答案

我必须要肯定同意Felix King和pimvdb。我认为使用Function.protoytpe.bind()函数的唯一缺点是,这不是所有浏览器(例如IE6)中都可用的函数。另一种方法是使用提供curry()函数的JavaScript库。另一种方法是定义一个函数,使您能够检索任何其他函数的调用函数。这是我在发布在我的博客上的定义对于我称之为getCall()的函数:

I have to definitely agree with both Felix King and pimvdb. I think the only drawback to using the Function.protoytpe.bind() function is the fact that this is not a function that is available in all browsers (IE6 for example). An alternative would be to use a JavaScript library that provides the curry() function. Another alternative would be to define a function which gives you the ability to retrieve the call function for any other function. Here is a definition that I posted on my blog for such a function which I called getCall():

Function.prototype.getCall = function() {
  var realFn = this;
  return function(objThis) {
    return realFn.apply(objThis, Array.prototype.slice.call(arguments, 1));
  };
};

现在,通过此定义,您可以执行以下操作来获取对该函数的调用函数的引用切片函数:

Now, with this definition, you could do the following to get a reference to the call function of the slice function:

var slice = [].slice.getCall();

这篇关于你如何引用Array.prototype.slice.call()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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