apply, call, bind在js中的区别
来源:互联网 发布:淘宝抠图出来衣服 编辑:程序博客网 时间:2024/05/18 21:47
apply, call, bind在js中的区别
在js中,这三种方法都是用来改变函数的this对象的指向的。
先看看相似点:
- 都是用来改变函数的this对象的指向的
- 第一个参数都是this要指向的对象
- 都可以继续传递参数
那区别呢?
上代码:
var xb = { name: '小冰', gender: '女', say: function(){ alert(this.name + ',' + this.gender); }}var other = { name: '小东', gender: '男',}xb.say(); ===> 结果 小冰,女
那么如果我们想要用xb的say()方法输出other的数据,要怎么办呢?
简单的可以用:
1. xb.say.call(other);2. xb.say.apply(other);3. xb.say.bind(other)();
由上面代码我们可以看到,其实call和apply方法,都是对函数的直接调用,但是bind()方法需要加上()来执行。
现在来看传参数的情况
上代码(还是上面的例子,但是传参):
var xb = { name: '小冰', gender: '女', say: function(school,grade){ alert(this.name + ',' + this.gender + '----' + school + ',' + grade); }}var other = { name: '小东', gender: '男',}
- 用call()传参调用
xb.say.call(other,'斯坦福','3')// ====> 小东,男----斯坦福,3
- 用apply()传参调用
xb.say.apply(other,['sitanfu','third']);// ====> 小东,男----sitanfu,third
从这里我们可以看到,其实,call()和apply()函数的用法其实是一样的,只是传参的形式不一样,这是他们最大的差别
bind()呢?
xb.say.bind(other,'斯坦福','3');// 是不是跟call传参很像
但是上面xb.say.bind(other,’斯坦福’,’3’),返回的其实还是一个函数,并没有执行
console.log(xb.say.bind(other)); // 我们可以把xb.say.bind(other);打印出来看看 // ===> 返回的是一个函数 返回放在下一节代码里面}
返回结果
function(school,grade){ alert(this.name + ',' + this.gender + '----' + school + ',' + grade);
所以要执行,需要在xb.say.bind(other)后面加()让其执行。执行结果如下:
console.log(xb.say.bind(other))('斯坦福','3'); // ==> 小东,男---斯坦福,3
这里附加bind的源码实现:
// the .bind method from prototype.jsFunction.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments),object = args.shift(); return function(){ return fn.apply(object,args.concat(Array.prototype.slice.call(arguments))); }}
2 0
- apply, call, bind在js中的区别
- JS中apply call bind的区别
- JS中call、apply、bind大概区别
- JS中call、apply、bind的区别
- js中的apply/call/caller/callee/bind
- JS中的call、apply、bind方法
- JS中的call、apply、bind方法
- JS中的call、apply、bind方法
- JS中的call、apply、bind方法详解
- 理解JS中的call、apply、bind方法
- JS中的call、apply、bind方法
- JS中的call、apply、bind方法
- 解析js中的call、apply、bind
- 理解JS中的call、apply、bind方法
- 理解JS中的call、apply、bind方法
- 浅谈JS中的call、apply和bind
- 理解JS中的call、apply、bind方法
- 深入理解js中的apply、call、bind
- 【杭电1862】excel排序
- Oracle常见错误:ORA-01403 的根本原因和解决方案
- [软件设计] 控制反转(Inversion of Control)随想
- Tiny6410学习—Linux命令
- Python学习(Leetcode 算法题解【1~20】)
- apply, call, bind在js中的区别
- [软件人生]关于公积金的用途
- Spring AOP的底层实现技术---JDK动态代理
- Servlet中请求转发forward与重定向sendRedirect
- 控制TextView滚动
- poj1724【最短路】
- java设计模式——装饰模式
- linux 入门教程(一)之linux目录结构
- I - the Sum of Cube