javascript - 关于JS中bind的实现
PHP中文网
PHP中文网 2017-04-11 11:00:41
[JavaScript讨论组]

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?
好抽象。
其实,代码一知半解,希望能有前辈能详细解释一下,感激不尽。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
巴扎黑

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方法返回的就是函数,不信你可以看代码的第一行

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号