
场景⛱
-
面试官🤵提问:“ 能不能简单实现call,bind,apply?”
-
求职者🙍♂️:“没问题!”
-
面试官 🤵:“来吧,展示”
一、call方法实现
思路🚩
- 接受多个参数,第一个为上下文,第二个及以后为函数本身参数
- 判断是否传入this
- 改变this指向
- 执行函数得到结果
- 删除this,避免全局污染
call简易代码🚀(Symbol,解构赋值)
Function.prototype.call1 = function (_this,...arg) {
const c = Symbol('c')
_this = _this||window
_this[c] = this
const result = _this[c](...arg)
delete _this[c]
return result
}
二、apply方法实现
思路🚩🚩
- 接受多个参数,第一个为上下文,第二个为函数本身参数(数组)
- 判断是否传入this
- 改变this指向
- 执行函数得到结果
- 删除this,避免全局污染
apply简易代码🚀(Symbol,解构赋值)
Function.prototype.apply1 = function (_this,arg) {
const a = Symbol('a')
_this = _this||window
_this[a] = this
const result = _this[a](...arg)
delete _this[a]
return result
}
三、bind方法实现
思路🚩🚩🚩
- 继承原型
- 更改this
- 合并argument并传递
bind简易代码🚀(instanceof,slice,concat)
Function.prototype.bind1 = function (_this,arg) {
const that = this
var fn = function () {
that.apply(this instanceof that?this :_this,arg.concat(Array.prototype.slice.call(arguments)))
}
fn.prototype = that.prototype
return fn
}
小结🎖
- 都是改变this的指向,要注意它们之间的区别
- 在改变this指向的同时也要注意argument的处理
点赞支持👍