核心思路:
1、函数方法调用 需要挂载到Funtion构造函数的prototype上
手写call
Function.prototype.myCall = function(ctx,...args){
// 判断ctx有没有传进来值 如果没有就赋值window
ctx = ctx || window
// 在传进来的对象上面新增一个属性 保存this
ctx._this = this
// 调用该函数、传参、保存
const resulte = ctx._this(args)
// 删除_this属性
delete ctx._this
// 返回 调用函数的结果
return resulte
}
手写apply
Function.prototype.MyApply = function (obj, arg) {
let fn = this //this表示函数
// 如果要是obj为undefined或者null时,设置其为window,
// 如果是基本数据类型,则将其设置为对象类型
let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
thisArg.fn = fn
arg = arg || [] //如果arg不存在,则直接赋值为[]
let res = thisArg.fn(...arg)
delete thisArg.fn
return res
}
手写bind
Function.prototype.MyBind = function(obj, ...args1) {
let fn = this
let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
return function(...args2) {
thisArg.fn = fn
let args = [...args1, ...args2]
let result = thisArg.fn(...args)
delete thisArg.fn
return result
}
}