call源码模拟
Function.prototype.call = function (context) {
const args = [...arguments].slice(1)
//使用一个对象属性模拟
const obj = context || window
const fn = Symbol("fn")
obj[fn] = this
const res = obj[fn](...args)
delete obj[fn]
return res
}
核心原理
- 看完代码之后我们就明白了
fn.call(context,args)
- 把fn里面的this指向context
- 创建一个对象target实际上就是context上面挂载一个fn
- 自然fn函数的实例就指向了它的对象也就是context
apply源码模拟
Function.prototype.apply = function (context, args = []) {
const obj = context || window
const fn = Symbol("fn")
obj[fn] = this
const res = obj[fn](...args)
delete obj[fn]
return res
}
bind源码模拟
核心原理
- 返回一个函数通过return function 闭包实现
- 通过调用apply将this指向传入的context
Function.prototype.bind = function() {
let args = Array.from(arguments)
let fn = this
let context = args.shift()
return function() {
let newArgs = Array.from(arguments)
return fn.apply(context,args.concat(newArgs))
}
}