首页 > 关于JS中bind的实现

关于JS中bind的实现

window.onload = function(){

    Function.prototype.bind = function(){
        var self = this,
        context = [].shift.call(arguments),
        args = [].slice.call(arguments);
        console.log(self);
        console.log(arguments);//[1,2]
        return function(){
            console.log(arguments);//[3,4]
            return self.apply(context,[].concat.call(args,[].slice.call(arguments)));
        };

    };
    var obj = {
        name:"keke"
    };
    var fun = function (a,b,c,d){
        alert(this.name);
        alert([a,b,c,d]);
    }.bind(obj,1,2);

    fun(3,4);
};

小白有问题如下:
1.var self=this中,this即为fun函数,原理是什么?
2.arguments为什么会不同,传参原理?
3.为何bind中返回的是一个function而不是直接返回self.apply?
好抽象。
其实,代码一知半解,希望能有前辈能详细解释一下,感激不尽。


fun调用bind方法时会先从自身属性上找,发现找不到,就会去fun.__proto__(内置原型)上找,内置原型引用的就是其构造方法的原型(Function.prototype),所以找到了Function.prototype.bind,于是就调用它。函数的this是在运行其间被指定的,所以此时的this就指向调用它的对象(fun)。

bind执行的时候传入了obj, 1, 2所以arguments就是这三个参数的数组(严格来说是类数组,有length属性,可以通过下标找到对应元素,但没有push,pop,shift,unshift方法)。
context = [].shift.call(arguments), //用shift方法取出第一个元素

args = [].slice.call(arguments);//将剩下的类数组元素转成真数组

最后一个问题就更简单了,Function.prototype.bind方法返回的就是函数,不信你可以看代码的第一行

【热门文章】
【热门文章】