前端百题斩【015】——快速手撕call、apply、bind

执鸢者 2021-06-15 22:51:31
面试 前端


公众号【执鸢者】提前解锁3斩
写该系列文章的初衷是“让每位前端工程师掌握高频知识点,为工作助力”。这是前端百题斩的第15斩,希望朋友们关注公众号“执鸢者”,用知识武装自己的头脑。

在百题斩【014】中已经简要概述了call、apply、bind三个方法,这三者作用是相同的,均可以改变this指向,从而让某对象可以调用自身不具备的方法,本节将深入理解这三者的实现原理。

15.1 call()

img

15.1.1 基础

call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。其返回值是使用调用者提供的this值和参数调用该函数的返回值,若该方法没有返回值,则返回undefined。

基本用法:

function.call(thisArg, arg1, arg2, ...)
小试牛刀
function method(val1, val2) {
return this.a + this.b + val1 + val2;
}
const obj = {
a: 1,
b: 2
};
console.log(method.call(obj, 3, 4)); // 10

15.1.2 实现

实现一个call函数,将通过以下几个步骤:
  1. 获取第一个参数(注意第一个参数为null或undefined时,this指向window),构建对象
  2. 将对应函数传入该对象中
  3. 获取参数并执行相应函数
  4. 删除该对象中函数,消除副作用
  5. 返回结果
Function.prototype.myCall = function (context, ...args) {
// 获取第一个参数(注意第一个参数为null或undefined时,this指向window),构建对象
context = context ? Object(context) : window;
// 将对应函数传入该对象中
context.fn = this;
// 获取参数并执行相应函数
let result = context.fn(...args);
// 消除副作用
delete context.fn;
// 返回结果
return result;
}
// ……
console.log(method.myCall(obj, 3, 4)); // 10

15.2 apply()

img

15.2.1 基础

apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。其返回值是指定this值和参数的函数的结果。call()apply()的区别是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组

基本用法

func.apply(thisArg, [argsArray])
小试牛刀
function method(val1, val2) {
return this.a + this.b + val1 + val2;
}
const obj = {
a: 1,
b: 2
};
console.log(method.apply(obj, [3, 4])); // 10

15.2.2 实现

apply和call的区别主要是参数的不同,所以其实现步骤的call大体类似,如下所示:
Function.prototype.myApply = function (context, arr) {
context = context ? Object(context) : window;
context.fn = this;
let result = arr ? context.fn(...arr) : context.fun();
delete context.fn;
return result;
}
// ……
console.log(method.myApply(obj, [3, 4])); // 10

15.3 bind()

img

15.3.1 基础

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。该函数的返回值是一个原函数的拷贝,并拥有指定的this值和初始参数。

基本用法

function.bind(thisArg[, arg1[, arg2[, ...]]])
小试牛刀
function method(val1, val2) {
return this.a + this.b + val1 + val2;
}
const obj = {
a: 1,
b: 2
};
const bindMethod = method.bind(obj, 3, 4);
console.log(bindMethod()); // 10

15.3.2 实现

实现一个bind函数相对较复杂一些,应该注意以下几点:
  1. 能够改变this指向;
  2. 返回的是一个函数;
  3. 能够接受多个参数;
  4. 支持柯里化形式传参 fun(arg1)(arg2);
  5. 获取到调用bind()返回值后,若使用new调用(当做构造函数),bind()传入的上下文context失效。
Function.prototype.myBind = function (context, ...args) {
if (typeof(this) !== 'function') {
throw new TypeError('The bound object needs to be a function');
}
const self = this;
// 定义一个中装函数
const fNOP = function() {};
const fBound = function(...fBoundArgs) {
// 利用apply改变this指向
// 接受多个参数+支持柯里化形式传参
// 当返回值通过new调用时,this指向当前实例 (因为this是当前实例,实例的隐士原型上有fNOP的实例(fnop);fnop instanceof fNOP为true)
return self.apply(this instanceof fNOP ? this : context, [...args, ...fBoundArgs]);
}
// 将调用函数的原型赋值到中转函数的原型上
if (this.prototype) {
fNOP.prototype = this.prototype;
}
// 通过原型的方式继承调用函数的原型
fBound.prototype = new fNOP();
return fBound;
}

1.如果觉得这篇文章还不错,来个分享、点赞吧,让更多的人也看到

2.关注公众号执鸢者,与号主一起斩杀前端百题

版权声明
本文为[执鸢者]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000040179488

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless