Array.prototype.slice.call(arguments)
来源:互联网 发布:21端口入侵工具 编辑:程序博客网 时间:2024/04/27 14:46
我们知道,Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)如:
var a={length:2,0:'first',1:'second'};Array.prototype.slice.call(a);// ["first", "second"] var a={length:2};Array.prototype.slice.call(a);// [undefined, undefined]
再看call的用法,如下例子
var a = function(){ console.log(this); // 'littledu' console.log(typeof this); // Object console.log(this instanceof String); // true } a.call('littledu');
可以看出,call了后,就把当前函数推入所传参数的作用域中去了,不知道这样说对不对,但反正this就指向了所传进去的对象就肯定的了。到这里,基本就差不多了,我们可以大胆猜一下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;}最后,附个转成数组的通用函数
var toArray = function(s){ try{ return Array.prototype.slice.call(s); } catch(e){ var arr = []; for(var i = 0,len = s.length; i < len; i++){ //arr.push(s[i]); arr[i] = s[i]; //据说这样比push快 } return arr; }}arguments有一个不可枚举的属性callee(不能用for in读出,可用HasOwnProterty(name)来判断),arguments.callee为正被执行的 Function 对象。slice时己把当前函数指针copy了过去,所以args的第一个元素为函数类型。
function makeFunc() { var args = Array.prototype.slice.call(arguments); var func = args.shift(); return function() { return func.apply(null, args.concat(Array.prototype.slice.call(arguments))); };}
0 0
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- Array.prototype.slice.call(arguments)
- zookeeper分布式锁(十二)
- JBOD磁盘磁盘簇
- Perl Tk grid布局管理器<1>
- zend framework2 redis使用遇到的问题
- 设屏幕自适应
- Array.prototype.slice.call(arguments)
- Spring 中transactionAttributes的合理配置
- 桂林北大青鸟平面设计
- -我爱校园作文400字-
- android手势创建及识别
- 给手游开发者的7个建议
- 进制间的相互转换
- gitlab搭建问题总结
- 经典SQL语句大全