bind , call and apply
来源:互联网 发布:电路板制作软件 编辑:程序博客网 时间:2024/05/09 16:37
之前记录过神奇的this,我们要想随着自己的意愿掌控this,那就需要这三个小帮手,哈哈,bind call and apply.
look a example please:
var a = { user:"路飞", fn:function(){ console.log(this.user); }}var b = a.fn;b(); //undefinedb.call(a);//路飞b.apply(a);//路飞var a = { user:"路飞", fn:function(e,ee){ console.log(this.user); //路飞 console.log(e+ee); //3 }}b.call(a,1,2);b.apply(a,[1,2]);var arr = [500,20];b.apply(a,arr);
如果直接运行b();输出的一定是undefined.
call(a,b,c,d)有多个参数,a:要将b添加到哪个环境中,this就会指向这个对象,剩下的参数任意。
apply和call类似,只是参数的形式不同而已,它的第二个参数要求一定是数组。
注意如果call和apply的第一个参数写的是null,那么this指向的是window对象
bind的用法和它们两个略有不同
var a = { user:"路飞", fn:function(){ console.log(this.user); }}var b = a.fn;b.bind(a);这样是输不来结果的,这就是bind和call、apply方法的不同,实际上bind方法返回的是一个修改过后的函数
var a = { user:"路飞", fn:function(){ console.log(this.user); //路飞 }}var b = a.fn;var c = b.bind(a);c();同样bind也可以有多个参数,并且参数可以执行的时候再次添加,但是要注意的是,参数是按照形参的顺序进行的。
var a = { user:"路飞", fn:function(e,d,f){ console.log(this.user); //路飞 console.log(e,d,f); //10 1 2 }}var b = a.fn;var c = b.bind(a,10);c(1,2);call和apply都是改变上下文中的this并立即执行这个函数,bind方法可以让对应的函数想什么时候调就什么时候调用,并且可以将参数在执行的时候添加,这是它们的区别,根据自己的实际情况来选择使用。接到的参数的使用是类似。的。
0 0
- bind , call and apply
- call apply 与 bind
- call()、apply()、bind()
- apply bind call区别
- call,apply,bind
- 【JavaScript】call, apply, bind
- bind apply call异同
- apply call bind区别
- JS call bind apply
- call()、apply()与bind()
- call apply bind
- call()、apply()、bind()详解
- bind apply call
- apply,call,bind
- apply、call、bind
- call,apply,bind
- bind&call&apply
- bind、apply、call解析
- Ajax+php的例子
- 递归计算1-100的数
- 【图割】opencv中构建图和最大流/最小割的gcgraph.h源码解读
- 在linux-suse上面安装db2
- Map
- bind , call and apply
- React-FileUpload 教程
- ZendStudio && Eclispe 解决svn导出项目乱码问题
- C實踐項目2.4—圓柱體的表面積
- Logcat输出到文件
- JavaWeb学习总结(五十)——文件上传和下载
- 乱斗西游开发经验分享(技术篇)
- 有个
- View的位置参数