Javascript ⼿写 call、apply 及 bind 函数
问题
Javascript ⼿写 call、apply 及 bind 函数
答案
⾸先从以下⼏点来考虑如何实现这⼏个函数
- 不传⼊第⼀个参数,那么上下⽂默认为 window
- 改变了 this 指向,让新的对象可以执⾏该函数,并能接受参数
实现 call
- ⾸先 context 为可选参数,如果不传的话默认上下⽂为 window
- 接下来给 context 创建⼀个 fn 属性,并将值设置为需要调⽤的函数
- 因为 call 可以传⼊多个参数作为调⽤函数的参数,所以需要将参数剥离出来
- 然后调⽤函数并将对象上的函数删除
Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
const args = [...arguments].slice(1)
const result = context.fn(...args)
delete context.fn
return result
}
apply实现
apply 的实现也类似,区别在于对参数的处理
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
let result
// 处理参数和 call 有区别
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
bind 的实现
bind 的实现对⽐其他两个函数略微地复杂了⼀点,因为 bind 需要返回⼀ 个函数,需要判断⼀些边界问题,以下是 bind 的实现
bind 返回了⼀个函数,对于函数来说有两种⽅式调⽤,⼀种是直接调⽤,⼀种是通过 new 的⽅式,我们先来说直接调⽤的⽅式
对于直接调⽤来说,这⾥选择了 apply 的⽅式实现,但是对于参数需要注意以下情况: 因为 bind 可以实现类似这样的代码 f.bind(obj, 1)(2) ,所以我们需要将两边的参 数拼接起来,于是就有了这样的实现 args.concat(…arguments)
最后来说通过 new 的⽅式,在之前的章节中我们学习过如何判断 this ,对于 new 的 情况来说,不会被任何⽅式改变 this ,所以对于这种情况我们需要忽略传⼊的 this
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
// 返回⼀个函数
return function F() {
// 因为返回了⼀个函数,我们可以 new F(),所以需要判断
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}
更多面试题
如果你想了解更多的前端面试题,可以查看本站的WEB前端面试题 ,这里基本包涵了市场上的所有前端方面的面试题,也有一些大公司的面试图,可以让你面试更加顺利。
面试题 | ||
---|---|---|
HTML | CSS | JavaScript |
jQuery | Vue.js | React |
算法 | HTTP | Babel |
BootStrap | Electron | Gulp |
Node.js | 前端经验相关 | 前端综合 |
Webpack | 微信小程序 | - |
这些题库还在更新中,如果你有不错的面试题库欢迎分享给我,我整理后放上来;人人为我,我为人人,互帮互助,共同提高,祝大家都拿到心仪的Offer!