最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is array slice method called using "call"? - Stack Overflow

programmeradmin0浏览0评论

As seen in this SO question

Function.prototype.bind = function(){ 
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); 
  return function(){ 
    return fn.apply(object, 
      args.concat(Array.prototype.slice.call(arguments))); 
  }; 
};

In this example why is it coded as

args = Array.prototype.slice.call(arguments)

will it be ok if I do

args = arguments.slice();

I am just trying to understand any specific reason for using call

And also what would be some other scenario where we will have to use Array.prototype.slice.call(arguments) ?

As seen in this SO question

Function.prototype.bind = function(){ 
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); 
  return function(){ 
    return fn.apply(object, 
      args.concat(Array.prototype.slice.call(arguments))); 
  }; 
};

In this example why is it coded as

args = Array.prototype.slice.call(arguments)

will it be ok if I do

args = arguments.slice();

I am just trying to understand any specific reason for using call

And also what would be some other scenario where we will have to use Array.prototype.slice.call(arguments) ?

Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Sep 15, 2015 at 15:01 sabithpockersabithpocker 15.6k1 gold badge43 silver badges77 bronze badges 2
  • 1 Why not simply try calling arguments.slice()...? – deceze Commented Sep 15, 2015 at 15:05
  • @deceze he he :) I was so damn sure that arguments is an array! – sabithpocker Commented Sep 15, 2015 at 15:06
Add a ment  | 

2 Answers 2

Reset to default 12

arguments is an array-like object, it is not an Array. As such, it doesn't have the slice method. You need to take the slice implementation from Array and call it setting its this context to arguments. This will return an actual Array, which is the whole point of this operation.

arguments is not an array :

function a(){console.log(typeof(arguments)) }

So this a(123) will yield object

So we borrow the method which can deal with array like object , to slice the object for as as if it was true array.

Borrowing can be made via call or apply.

apply will send arguments as an array ( remember : a for array) - while call will send params as ma delimited values.

发布评论

评论列表(0)

  1. 暂无评论