javascript - js中的bind
天蓬老师
天蓬老师 2017-04-11 10:02:03
[JavaScript讨论组]

求大神解释下js中的bind的用法,他和callapply都有哪些区别

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(2)
高洛峰

先来个总结

apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
apply 、 call 、bind 三者都可以利用后续参数传参;
bind是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

绑定bind的ES3实现

if(!Function.prototype.bind){
    Function.prototype.bind = function(o, args){
        
        var self = this,
            boundArgs = arguments;
        
        return function(){                 //此时返回的只是一个函数
            var args = [], i;
            for(var i=1; i< boundArgs.length; i++){  
                 args.push(boundArgs[i]);
            }
            for(var i =0; i< arguments.length; i++){
                 args.push(arguments[i]);
            }
            return self.apply(o, args);    
        }

    }

}
var sum = function(x,y){ return x+y };
var result = sum.bind(null,1);
result(2);   // 3
黄舟

bind 是固定某个函数的参数和this,返回另外一个函数。
callapply是指定this和参数调用这个函数,立即执行这个函数。
call apply 的区别是他们指定参数的方式不同。
比如

function fn(a,b){
    console.log(this);
    console.log(a);
    console.log(b);
}
// bind(this,args...)
bf = fn.bind("Bind this",10); // 没有任何输出,也就是说没有执行这个函数
bf(); // "Bind this",10,undefined
bf(20);// “Bind this”,10,20
// 原函数不受影响
fn(1,2); //window, 1,2
bf2 = fn.bind("Bind this",1,2);
bf2(); // "Bind this",1,2

// call(this,args...)
fn.call("Call this",1) // "Call this",1,undefined
fn.call("Call this",1,2) // "Call this",1,2

// apply(this,[args])
fn.apply("Apply this",[1]) // "Apply this",1,undefined
fn.apply("Apply this",[1,2]) // "Apply this",1,2
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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