// 定义一个 show 方法
function show(...args) {
console.log(this);
}
// 原型上新增一个 myCall 方法
Function.prototype.myCall = function (ctx, ...args) {
// console.log(this);//此时 this 指向 show 方法
ctx.fn = this//把 show 方法赋值给 ctx 上的一个属性 fn 方法
ctx.fn(...args)//调用 fn 方法,对象上方法,谁调用 this 指向谁,所以此时 this 指向 ctx,就是传入进来的新对象 {name:'zs'}
delete ctx.fn//删除该属性
}
// 调用 myCall 方法并传入一个新的对象
// call 方法传参方式:
// 参数1:对象
// 参数2,参数3.......:多个属性一一传值
show.myCall({ name: 'zs' }, '参数1', '参数2', '参数3')
// 原型上新增一个 myApply 方法
Function.prototype.myApply = function (ctx, args) {
if (args && !(args instanceof Array)) throw ('myApply方法只接受数组作为参数')
ctx.fn = this
ctx.fn(args)
delete ctx.fn
}
// apply 方法传参方式:
// 参数1:对象
// 参数2:数组(多个属性作为数组的成员项)
show.myApply({ name: 'zs' }, ['参数1', '参数2', '参数3'])
// 原型上新增一个 bind 方法
Function.prototype.myBind = function (ctx, ...args1) {
// bind 返回一个新的函数,需要再次调用
return (...args2)=>{
ctx.fn=this
ctx.fn(...args1.concat(args2))
delete ctx.fn
}
}
// bind 方法传参方式:
// 参数1:对象
// 参数2,参数3.......:多个属性一一传值
//
const bind=show.myBind({ name: 'zs' }, '参数1', '参数2', '参数3')
// bind 返回一个新的函数,需要再次调用
bind('参数4')
手写 call apply bind
最新推荐文章于 2024-10-06 13:20:09 发布