扫码关注官方订阅号
求大神解释下js中的bind的用法,他和call和apply都有哪些区别
js
bind
call
apply
欢迎选择我的课程,让我们一起见证您的进步~~
先来个总结
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,返回另外一个函数。call 和 apply是指定this和参数调用这个函数,立即执行这个函数。call apply 的区别是他们指定参数的方式不同。比如
this
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
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
先来个总结
绑定bind的ES3实现
bind是固定某个函数的参数和this,返回另外一个函数。call和apply是指定this和参数调用这个函数,立即执行这个函数。callapply的区别是他们指定参数的方式不同。比如