一、call函数

模拟实现第一步:整体思路

Function.prototype.call2=function(context){
context.fn=this; //1、将函数(谁调用 即this)设为对象(参数)的属性
context.fn(); //2、执行该函数
delete context.fn;//3、删除对象中的函数属性
}

模拟实现第二步:加上参数

Function.prototype.call2 = function(context) {
context.fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']'); //// 执行后 args为 ["arguments[1]", "arguments[2]", "arguments[3]"]
}
eval('context.fn(' + args +')'); //这里 args 会自动调用 Array.toString() 这个方法。
delete context.fn;
}

模拟实现第三步:一些小问题

Function.prototype.call2 = function (context) {
var context = context || window; //this 参数可以传 null,当为 null 的时候,视为指向 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;
}
Function.prototype.call = function (context, ...args) {
var context = context || window;
context.fn = this; var result = eval('context.fn(...args)'); //采用ES6的语法 delete context.fn
return result;
}

二、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;
}
Function.prototype.apply = function (context, arr) {
let context = context || window;
context.fn = this;
let result = eval('context.fn(...arr)'); delete context.fn
return result;
}

最新文章

  1. node.js操作mysql数据库之增删改查
  2. JavaScript类型判断instanceof与typeof对比
  3. 动态规划(DP)
  4. Git常用
  5. ASP.NET 5探险(5):利用AzureAD实现单点登录
  6. 开启telnet的几种方法
  7. javascript: detect mobile devices or browser
  8. R语言画图基础参数设置
  9. (转)Sqlite 管理工具 SQLiteDeveloper及破解
  10. LA 3713
  11. -_-#【缓存】Content-Type 错误
  12. 转:DSP学习经验
  13. jquery 的ready() 与window.onload()的区别
  14. centos扩容(pv,vg,lv)
  15. java分割字符串用法
  16. [Swift]LeetCode381. O(1) 时间插入、删除和获取随机元素 - 允许重复 | Insert Delete GetRandom O(1) - Duplicates allowed
  17. 一个数组中两个数的和为N,找出这两个数字的下标
  18. JAVA常用设计模式(一、抽象工厂模式)
  19. JavaScript实现iphone时钟
  20. LightOJ - 1246 Colorful Board(DP+组合数)

热门文章

  1. Django学习路31_使用 locals 简化 context 写法,点击班级显示该班学生信息
  2. sqlzoo - SELECT from WORLD Tutorial 答案
  3. PHP uksort() 函数
  4. PHP date_offset_get() 函数
  5. PHP gd_info - 取得当前安装的 GD 库的信息
  6. C/C++编程笔记:C语言入门知识点(一),请收藏C语言最全笔记!
  7. 2020牛客暑假多校训练营 第二场 G Greater and Greater bitset
  8. EC R 87 div2 D. Multiset 线段树 树状数组 二分
  9. Pr剪辑
  10. MVC + EFCore 项目实战 - 数仓管理系统9 - 数据源管理完结篇