前言
今天偶然翻资料看到一个叫做软绑定的函数,用来确定this的;
原代码
if(!Function.prototype.softBind){
Function.prototype.softBind = function(obj){
var fn = this;
var curried = [].slice.call(arguments,1);
var bound = function(){
return fn.apply(
(!this || this === (window || global)) ? obj:this,
curried.concat.apply(curried,arguments);
)
};
bound.prototype = Object.create(fn.prototype);
return bound;
}
}
看到[].slice.call(arguments,1)
这个写法我一脸懵逼,为何?
arguments是一个对象而不是数组..而且自身的原型链上也没有slice这个方法;
个人见解
- []自身也是也是一个对象.而数组原型链上有这个slice这个方法,通过call显式绑定来实现arguments变相有slice这个方法
/*此处的返回值是true*/
[].slice === Array.prototype.slice;
/*确定arguments的类型
* 返回 3,Object, true;
*/
(function(a,b,c){
console.log(arguments.length);
console.log(typeof arguments);
console.log( arguments instanceof Object);
}(1,2,3))
/*我们自身也可以模拟一个对象传入,我们这里用数组对象,不是等同,只是道理差不多的*/
aargument = [1,2,3,4];
[].slice.call(aargument,3); //返回[4]
[].slice.call(aargument,1,3); //[2, 3]
总结
那个写法就是裁切arguments传入的参数,保存起来操作;