欢迎访问我的个人博客:http://www.xiaolongwu.cn

Array.prototype.slice.call(arguments)的作用为:强制转化arguments为数组格式,一般出现在框架活插件的源码中

如何理解

上面的代码等价于[ ].slice.call(arguments)

或者随便一个数组调用都行 [1,2,4].slice.call(arguments)

因为,前面的调用者的作用只是沿着原型链向上找,最终找到Array为止,slice为Array原型上的一个方法

slice内部的实现原理大概是这样的

Array.prototype.slice = function(start,end){
var result = new Array();
start = start || 0; // 如果不传则取默认值
end = end || this.length; // 如果不传则取默认值 //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键
for(var i = start; i < end; i++){
result.push(this[i]);
}
return result;
}

数组和字符串都有slice方法

如果对slice不是很了解,请看这篇文章:slice()与splice()的用法和区别你清楚吗?

call方法的作用为:改变调用者的this指向并且执行调用者,

    function fn(a){
console.log(this.a);
console.log(this);
} var obj = {
a : 2
} fn.call(obj); // 2
// {a : 2}
// 解释一下 fn的this指针指向了obj ,并且执行了fn函数

如果对call方法还是没理解,请看这边文章 js基础--深入理解call、apply、bind

arguments 为函数实参的一个集合,数据类型为对象类型

写一个例子吧

    function ary(){
console.log(arguments,typeof arguments,arguments instanceof Object) // 自己实操一下 看看上面这行代码能打印出什么 return [11,12].slice.call(arguments); //这里的[11,12]可以被替换为任意的数组,不影响结果
} var a11 = ary(1,2,3,4,5,6,888,9,222); console.log(a11); [1, 2, 3, 4, 5, 6, 888, 9, 222]
console.log(typeof a11); //"object"
console.log(a11 instanceof Array); //ture

技术延伸

其实要实现将arguments强制转化为数组,还有几种方式

利用es6的Array.from()

    function fn(){
var a = Array.from(arguments);
var b = Array.from(arguments).slice(1);
console.log(a);
console.log(b);
} fn(1,2,6,3,4,12);
// 结果分别为 1,2,6,3,4,12 和 2,6,3,4,12

利用es6的展开表达式

    function fn(){
var a = [...arguments];
var b = [...arguments].slice(1);
console.log(a);
console.log(b);
} fn(1,2,6,3,4,12);
// 结果分别为 1,2,6,3,4,12 和 2,6,3,4,12

本文完


github资源地址:https://github.com/关于Array.prototype.slice.call(arguments) 的思考.md

我的个人博客:http://www.xiaolongwu.cn

csdn博客地址:https://blog.csdn.net/wxl1555

如果您对我的博客内容有疑惑或质疑的地方,请在下方评论区留言,或邮件给我,共同学习进步。

邮箱:wuxiaolong802@163.com

最新文章

  1. XCode6 生成prefix.pch文件
  2. 利用POI 技术动态替换word模板内容
  3. Object-relational mapping
  4. [terry笔记]Oracle会话追踪(一):SQL_TRACE&amp;EVENT 10046
  5. Entity Framework 使用注意:Where查询条件中用到的关联实体不需要Include
  6. java_闭包和回调实现一边按键盘一边演讲
  7. Config
  8. SharePoint 2010以其他用户身份登录的弹出代码
  9. Node.js v0.10.31API手冊-事件
  10. MySQL &#183; 引擎特性 &#183; InnoDB Buffer Pool
  11. Hbase 技术细节笔记(上)
  12. Android简易实战教程--第十五话《在外部存储中读写文件》
  13. termios结构体的内容
  14. 最小生成树模板题 hpu 积分赛 Vegetable and Road again
  15. 这里已不再更新,访问新博客请移步 http://www.douruixin.com
  16. InnoDB锁笔记
  17. 1--Python 入门--Python基础数据类型
  18. MySql5.5 SQL优化 慢查询日志存储
  19. ES6的一些基本用法
  20. V-rep学习笔记:main script and child scripts

热门文章

  1. 开源视频监控系统:iSpy
  2. InfoQ访谈:Webkit和HTML5的现状和趋势
  3. Linux C OSS音频编程
  4. 【matlab编程】Matlab版扫雷
  5. 嵌入式C语言查表法的项目应用
  6. mysql进阶(十四) 批量更新与批量更新多条记录的不同值实现方法
  7. cocos2d-x 读写 xml 文件
  8. ITU-T Technical Paper: NP, QoS 和 QoE的框架以及它们的区别
  9. SharePoint 调用WebService操作List小记
  10. rails将类常量重构到数据库对应的表中之二