// call apply bind 都是 function 原型上的方法
// call 传入 this指向的对象 传入参数 列表
Function.prototype.myCall = function (context,...args){
if (context===null||typeof context === undefined){
context = window //如果 context 传入 null 或 undefined 则 this 指向 window
}
//传入值为对象
context.f = this //用自定义键保存this
console.log(context,args)
const res = context.f(...args)//call 传入参数列表
delete context.f // 执行完方法后删除属性 (调用一次会向context上添加一次属性,多次调用后context上属性会过多)
return res //将结果返回
}
// function A(a){
// this.a = a
// console.log(a)
// }
// function B(a){
// A.myCall(this,a,2,3,4)
// console.log(a)
// }
// B(1)//test
//apply 与call的唯一区别 传入 数组或数组对象
Function.prototype.myApply = function(context,args){
if (context===null||typeof context === undefined){
context = window //如果 context 传入 null 或 undefined 则 this 指向 window
}
// //传入值为对象
context.f = this //用自定义键保存this
console.log(context,args)
const res = context.f(args)//传入数组参数
delete context.f
return res
}
//function A(a){
//this.a = a
//console.log(a)
//}
//function B(a){
// A.myCall(this,a,2,3,4)
//A.myApply(this,a,1,2,3)
//console.log(a)
//}
// B(1)//test
//bind 返回 一个新函数
Function.prototype.myBind = function (context,...args) {
//保存 this
let that = this
//返回一个函数
return function f(...param) {
//param 是调用方法的实例本身的参数
// 判断是否做为 构造函数使用
if(that instanceof f){
// return that.apply(this,...param,...args) //直接 new 更简洁
return new f(...param,...args) //返回一个 实例 将参数全传给实例
}
return that.apply(context,...args,...param) //不是构造函数 改变指向 将参数传给 返回函数
}
}
//const c = {
//x: 42,
//getX: function() {
//return this.x;
//}
//};
//const X = c.getX;
//console.log(X());
//const GetX = X.myBind(c);
//console.log(GetX());
实现 call apply bind
最新推荐文章于 2024-07-29 16:08:41 发布
这篇博客介绍了如何在JavaScript中手动实现`call`、`apply`和`bind`这三个函数原型上的方法。通过这些自定义实现,读者可以更好地理解它们的工作原理。`myCall`接收一个上下文对象和参数列表,`myApply`接收上下文和一个参数数组,而`myBind`返回一个新的函数,保持指定的上下文并可预设参数。示例中展示了如何使用这些方法来调用和绑定函数。
摘要由CSDN通过智能技术生成