// 模拟实现call方法
Function.prototype.call2 = function (context) {
var context = context || window;
context.fn = this; var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
} var result = eval('context.fn(' + args +')'); delete context.fn
return result;
} // 测试一下
var value = 2; var obj = {
value: 1
} function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
} bar.call(null); // 2 console.log(bar.call2(obj, 'kevin', 18));
// 模拟实现apply方法
Function.prototype.apply = function (context, arr) {
var context = Object(context) || window;
context.fn = this; var result;
if (!arr) {
result = context.fn();
}
else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')')
} delete context.fn
return result;
}
// 模拟实现Bind方法
Function.prototype.bind = function (oThis) {
var aArgs = Array.prototype.slice.call(arguments, 1);
var fToBind = this;
var fNOP = function () {};
var fBound = function () {
fBound.prototype = this instanceof fNOP ? new fNOP() : fBound.prototype;
return fToBind.apply(this instanceof fNOP ? this : oThis || this, aArgs )
}
if( this.prototype ) {
fNOP.prototype = this.prototype;
}
return fBound;
}

三者的区别:

  • 三者都是用来改变函数的this指向
  • 三者的第一个参数都是this指向的对象
  • bind是返回一个绑定函数可稍后执行,callapply是立即调用
  • 三者都可以给定参数传递
  • call给定参数需要将参数全部列出,apply给定参数数组

最新文章

  1. .Net环境下的缓存技术介绍
  2. struts2升级报ActionContextCleanUp&lt;&lt;is deprecated。Please use the new filters
  3. oracle触发器自增字段
  4. centos6.5版本改系统语言成中文简体
  5. 最大流isap模板
  6. “华尔街之狼”:ICO是“史上最大骗局”
  7. MVC、MVP以及MVVM分析
  8. Webpack的配置与使用
  9. 2. Dubbo原理解析-Dubbo内核实现之基于SPI思想Dubbo内核实现(转)
  10. CM记录-Hadoop参数调优
  11. urllib 获取页面或发送信息
  12. synchronized的四种用法
  13. effective C++ 读书笔记 条款08
  14. 关于session_cache_expire 的理解
  15. 使用Bulk Binding批量绑定的模式高效处理ORACLE大量数据
  16. ViewPager滑动不畅及灵敏度的问题
  17. git call failed: [git clone Could not resolve host: git.openstack.org
  18. ptthon 网络编程
  19. unity3d的NGUI简易登录界面
  20. Java使用TCP聊天程序

热门文章

  1. jdbc封装工具类(连接池)
  2. git将本地文件上传到远程仓库
  3. 设置cudnn日志
  4. c++ 函数篇
  5. linux系统安装谷歌浏览器设置开机自动启动并打开指定页面
  6. ISTQB软件测试初级认证模拟题
  7. Day 22 22.1.1:增量式爬虫 - 场景1的实现
  8. Word10 个人简历office真题
  9. Something Just Like This
  10. docker打包java