函数适用于使用切片的参数 [英] Function apply with arguments using slice
问题描述
查看这个教程我在一个评论中看到了以下代码建议:
Looking at this tutorial I saw the following code suggestion in one comment:
init:function(callback){
var that =this ;
return $http.jsonp(this.url).success(
function(data){
that.availableGenres = that.getGenres(data);
that.results = that.getResults(data);
if(callback)callback.apply(null,[].slice.call(arguments))
}
)
}
但这行 callback.apply(null,[]。slice.call(arguments))
看起来很奇怪。
为什么不只是: callback.apply(null,arguments)
?因为我不喜欢当我不明白我用这个 小提琴 来理解那里的 slice
函数的需要。但它给了我同样的结果,我仍然没有得到它。
Why not just: callback.apply(null, arguments)
? Because I don't like when I don't understand the point of something I played around with this Fiddle to understand the need of slice
function in there. But it gives me the same result and I still do not get it.
任何人都知道为什么需要 slice ?
Anyone knows why slice
is needed?
推荐答案
您并不需要它,传递 arguments
to apply
。
You don't really need it, passing arguments
to apply
directly is fine.
它被指定允许在 EcmaScript 3 和 EcmaScript 5 甚至允许任何类似数组的对象不仅仅是数组和参数对象。也许它需要与更早或更多的JS实现向后兼容。另外,(正如你从其他答案中看到的那样),有些人不知道这个事实,认为他们需要传递实际的数组 - 所以他们是不必要的小心。
It is specified to be allowed in EcmaScript 3, and EcmaScript 5 even allows any array-like objects not only arrays and arguments objects. Maybe it was needed to be backwards-compatible with even earlier or buggy JS implementations. Also, (as you see from the other answers), some people don't know about this fact and think they would need to pass actual arrays - so they are unnecessary careful.
这篇关于函数适用于使用切片的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!